I defined the following class:
class A {
int a;
public:
A(int _a = 0) :a(_a){}
A(initializer_list<int> il) :a(il.size()){}
friend A operator+(const A& a1, const A& a2);
};
A operator+(const A& a1, const A& a2){ return A(); }
The following client code
A a;
operator+(a,{3, 4, 5});
can compile, but the following
A a;
a + {3, 4, 5};
can not compile. The error message is "error C2059: syntax error : '{'" and "error C2143: syntax error : missing ';' before '{'".
Both two client codes try to do the implicit type conversion, from initialization list {3,4,5} to class A, but the first succeeds while the second snippet fails. I can not understand why.
Can you explain it?
I'm using MS Visual Studio 2013 Update 4.
[Edit]
Here is a follow up, after reading the comments and other related materials. I think my question can now be reduced to the following:
I got it that brace-init-list is not allowed in the RHS of an binary expression, and also that it IS allowed in a function call. The thing is, I think the binary expression, say, arg1 + arg2 is converted internally by the compiler to a function call operator+ (arg1, arg2), especially when arg1 is a class type. So at this point, there is no difference between binary expression and function call. As a result, the only explanation I can figure out is that there is a preventing rule applied before such a binary-expression-to-function-call conversion, that checks particularly whether the second argument is a brace-init-list or not. If it is, conversion to an equivalent function call will be forbidden and an error is produced. I wonder if these conjectures are real and if it is, is it written somewhere specifically in the C++ standard? Thank everyone who participated in my question.
{3, 4, 5}is a braced-init-list. A braced-init-list is not an expression; the syntax only allows it in a limited number of places, it cannot appear everywhere an integer literal may appear, say. In particular, it's allowed as an argument to a function call, and explicitly allowed on the right hand side of an assignment operator (5.18/9), but not any other operators.