I understand that, given a braced initializer, auto
will deduce a type of std::initializer_list
, while template type deduction will fail:
First of all it's "speculative explanations of the form "this could be the reason"" as you call it.
{1,2,3}
is not only std::initializer_list
but also allow initialize types without constructor. For example:
#include
struct x{
int a,b,c;
};
void f(x){
}
int main() {
f({1,2,3});
}
is correct code. To show that it isn't initializer_list
let's see the following code:
#include
struct x{int a,b,c;};
void f(x){
}
int main() {
auto il = {1, 2, 3};
f(il);
}
Error is:
prog.cpp: In function ‘int main()’:
prog.cpp:10:9: error: could not convert ‘il’ from ‘std::initializer_list’ to ‘x’
And now to the question "What is the difference?"
in auto x = {1, 2, 3};
code it's OK to determine type, because coder explicitly said "It's not important what's type it is" using auto
While in case of function template he may be sure that he is using different type. And it's good to prevent errors in ambiguous cases (It doesn't seem like C++ style , through).
Especially bad it will be in case when there was 1 function f(x)
and then it was changed to template one. Programmer wrote to use it as x
, and after adding new function for other type it slightly change to call completely different one.