mercredi 22 juin 2016

Narrowing conversion in pair with braced initializer compiling if second attribute is not braced-initialized


Since c++11, narrowing conversion is not allowed in list initialization (including aggregate initialization). So basically:

char c{1000}; // Does not compile with g++, clang, vc

But:

std::pair<char, double> p{1000, 1.0};

Compiles with all compiler?

But:

std::pair<char, double> p{1000, {1.0}};

Does not compile with VC (error C2398), gives a warning with clang and compiles silently with g++...

I would have expected VC behavior everywhere, i.e. a non-allowed narrowing conversion throwing an error. Which is compiler is right?


On the other hand, none of the variable declarations in the following snippets compile:

struct X {
    char c;
    double d;
};

X x1{999, 1.0};
X x2{999, {1.0}};

struct Y {
    char c;
    double d;
    Y (char c, double d) : c(c), d(d) { }
};

Y y1{999, 1.0};
Y y2{999, {1.0}};

So one of my guess may be that there is something special about std::pair? Something that would also narrowing braced-initialization?


Aucun commentaire:

Enregistrer un commentaire