Why is there no implicit conversion sequence from int to vector<double>?

109 views Asked by At

Regarding

vector<double> v2 = 9; //error: no conversion from int to vector

Is there no implicit conversion sequence of the copy-initialization from

int

to

vector<double>

because

std::vector<double>(int)

is explicit?

Would it have been possible to have had a type conversion of type floating-integral conversion in the case of it not having been declared explicit?

1

There are 1 answers

1
Clifford On

It would be ambiguous and semantically unconventional if you expected

vector<double> v2 = 9;

to be equivalent to

vector<double> v2( 9 ) ;

The latter does not assign a value of 9 to v2, the parameter is not an initialiser, rather it sets the length of the vector with initialised values determined by the default constructor of the type. To create a vector with a single initial value 9 would require:

vector<double> v2( 1, 9 ) ;

or

std::vector<double> v2 { 9 } ;

Initialisation with = should conventionally have similar semantics to assignment, and in that case v2 = 9 would be equally semantically ambiguous, or at least syntactically inconsistent. Just as you cannot assign a single value to an array without an index, you should not expect to assign one to a vector. Of course such a thing could have been defined, but would be confusing semantically.