c++ - Implicit type conversion from initialization list compiles in one case but does not in another -
i defined following class:
class { int a; public: a(int _a = 0) :a(_a){} a(initializer_list<int> il) :a(il.size()){} friend operator+(const a& a1, const a& a2); }; operator+(const a& a1, const a& a2){ return a(); }
the following client code
a a; operator+(a,{3, 4, 5});
can compile, following
a a; + {3, 4, 5};
can not compile. error message "error c2059: syntax error : '{'
" , "error c2143: syntax error : missing ';' before '{'
".
both 2 client codes try implicit type conversion, initialization list {3,4,5}
class a
, first succeeds while second snippet fails. can not understand why.
can explain it?
i'm using ms visual studio 2013 update 4.
[edit] here follow up, after reading comments , other related materials. think question can reduced following: got brace-init-list not allowed in rhs of binary expression, , allowed in function call. thing is, think binary expression, say, arg1 + arg2
converted internally compiler function call operator+ (arg1, arg2)
, when arg1 class type. @ point, there no difference between binary expression , function call. result, explanation can figure out there preventing rule applied before such binary-expression-to-function-call conversion, checks particularly whether second argument brace-init-list or not. if is, conversion equivalent function call forbidden , error produced. wonder if these conjectures real , if is, written somewhere in c++ standard? thank participated in question.
the error message generated clang quite clear:
error: initializer list cannot used on right hand side of operator '+'
looking c++11 standard, find (8.5.4/1 [dcl.init.list]):
note: list-initialization can used
- as initializer in variable definition (8.5)
- as initializer in new expression (5.3.4)
- in return statement (6.6.3)
- as function argument (5.2.2)
- as subscript (5.2.1)
- as argument constructor invocation (8.5, 5.2.3)
- as initializer non-static data member (9.2)
- in mem-initializer (12.6.2)
- on right-hand side of assignment (5.17)
so guess braced-init-list can used in cases listed above. operator+(a, {1, 2, 3})
works because of case 4. a = {1, 2, 3}
works because of last case. nothing mentioned a + {1, 2, 3}
. no.
Comments
Post a Comment