What is the difference between std :: initializer_list <int> ({1,2,3}) and {1,2,3}?

I have the following template function:

template<typename T> void foo2(T t) {} 

I know that I can not name it using:

 foo2({1,2,3}); 

because the list of initializers is a non-deduced context for the template argument. I have to use:

 foo2<std::initializer_list<int>>({1,2,3}); 

but I can also use:

 foo2(std::initializer_list<int>({1,2,3})); 

what makes me wonder what is the difference between: {1,2,3} and std::initializer_list<int>({1,2,3}) ?

+5
source share
1 answer

A braced-init list is not an expression and therefore has no type. When you call

 foo2({1,2,3}); 

the compiler does not know what type {1,2,3} represents in your mind, and therefore it does not compile.

 foo2<std::initializer_list<int>>({1,2,3}); 

compiles because the compiler doesn’t have to print the type here, you specified it, it is std::initializer_list<int> . Therefore, it can initialize t with {1,2,3} .

The third call also compiles because the compiler can infer type. std::initializer_list<int>({1,2,3}) , obviously, a std::initializer_list<int> , and therefore it can initialize t with the passed value pr.

+7
source

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


All Articles