Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function template deduction and initlializer_list

I have the following function template:

template <typename K, typename V>
void f(std::initializer_list<std::pair<const K, V>> il)
{
    //...
}

I call the function as follows:

f({std::pair<const int,int>(1,2), std::pair<const int,int>(3,4)});    //(a)

and it works fine.

However, if I try and call it as follows:

f({{1,2}, {3,4}});    //(b)

it is not able to deduce the correct type, and I get a compilation error along the lines of:

'no matching function for call to 'f(<brace-enclose initializer list>)
note candidate is:
note: template <class K, class V> void f(std::initializer_list<std::pair<const K, V>>)'

If I call it as follows:

f({std::pair<const int,int>(1,2), {3,4}});    //(c)

the type deduction works, but if I try and call it as follows:

f({std::make_pair(1,2), {3,4}});   //(d) 

I get the same compilation error as previously.

My question is:

Why does template type deduction work in (c) but not in (d)?

(Compiler is gcc v4.6.3, with flag -std=c++11)

I have looked at similar, older SO posts but they didn't appear to quite answer this question.

like image 804
TPJ Avatar asked Sep 30 '22 21:09

TPJ


1 Answers

The problem with b) is that the compiler isn't able to infer the types since something like

{1,2}

might as well be taken for an initializer_list<int>, the problem with d) is that make_pair won't generate a const int for the first part of the pair

like image 125
Marco A. Avatar answered Oct 03 '22 02:10

Marco A.