Why does vector <double> accept initializer_list with integer elements?
#include <iostream>
#include <vector>
int main()
{
// case I: uniform initialization
//
int ii = 100;
// Error: cannot be narrowed from type 'int' to 'double'
// in initializer list
//
double dd{ ii };
// case II: initializer_list
//
std::vector<double> vecDouble{ 1, 2.2 }; // fine!
// case III: initializer_list
//
std::vector<int> vi = { 1, 2.3 }; // error: double to int narrowing
// case IV: intializer_list
// cannot be narrowed from type 'int' to 'double'
//
std::vector<double> vecD2{ ii, 2.2 }; // Error
}
Why there is inconsistency here, where caseI does not accept int for double conversion, but caseII allows conversion.
+4
1 answer
In short, this works because the conversion from intto is doublenot a narrowing conversion. In other words, this works for the same reason why the following code works:
double x = 1;
The compiler must build std::initializer_list<E>to initialize the curly braces. He knows the type of Ehow double, because you are initializing std::vector<double>. This is described in detail in section 8.5.4 of the C ++ 11 standard.
Here is an example from section 8.5.4.3:
struct S {
S(std::initializer_list<double>); // #1
S(const std::string&); // #2
// ...
};
const S& r1 = { 1, 2, 3.0 }; // OK: invoke #1
:
- long double double float double float, , , , ( )
- , , ,
- , , , , , .
ii , int double, .
+4