Function template output 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 great.

However, if I try to call it like this:

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

it cannot infer the correct type, and I get a compilation error in the lines:

 '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 this way:

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

type inference works, but if I try and name it like this:

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

I get the same compilation error as before.

My question is:

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

(The compiler is gcc v4.6.3, with the flag -std = C ++ 11)

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

+5
source share
1 answer

The problem with b) is that the compiler cannot infer types because something like

 {1,2} 

can also be taken for initializer_list<int> , the problem with d) is that make_pair will not generate a const int for the first part of the pair

+4
source

Source: https://habr.com/ru/post/1202539/


All Articles