Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Class template deduction (P0091R0) for function arguments

Tags:

c++

c++17

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?

like image 626
Florian Schmid Avatar asked Nov 22 '16 16:11

Florian Schmid


1 Answers

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.

like image 125
Barry Avatar answered Nov 14 '22 11:11

Barry