vendredi 24 avril 2015

Implicit type conversion from initialization list compiles in one case but does not in another

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.

Aucun commentaire:

Enregistrer un commentaire