In C++17 we can do somthing like
std::pair p = {1,3}; // compiler deduces template parameters to pair<int,int>
From the documentation at cppreference I understand that the following will NOT work:
template<class T1, class T2>
void bar(std::pair<T1,T2>)
{}
void foo()
{
bar({1,3}); // No deduction of pair template arguments
}
Can anyone confirm this and give some insight, why this won't work? Technically this should work, right? Has there been any discussion to make this work, or is it kind of an oversight?
The reference is correct. Template argument deduction for class templates as currently adopted applies solely to declarations (and explicit type conversions - which are defined in terms of declarations), in [dcl.type.class.deduct]:
If a placeholder for a deduced class type appears as a decl-specifier in the decl-specifier-seq of a simple-declaration, the init-declarator of that declaration shall be of the form
declarator-id attribute-specifier-seqoptinitializer
The placeholder is replaced by the return type of the function selected by overload resolution for class template deduction (13.3.1.8). If the init-declarator-list contains more than one init-declarator, the type that replaces the placeholder shall be the same in each deduction. [ Example:
template<class T> struct container { container(T t) {} template<class Iter> container(Iter beg, Iter end); }; template<class Iter> container(Iter b, Iter e) -> container<typename std::iterator_traits<Iter>::value_type>; std::vector<double> v = { /* ... */}; container c(7); // OK, deduces int for T auto d = container(v.begin(), v.end()); // OK, deduces double for T container e{5, 6}; // error, int is not an iterator
—end example ]
There was nothing in the proposal or the adopted wording about deducing a class template specialization from a braced-init-list.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With