struct A
{
A(std::vector<int> x):
x_(std::move(x)) {}
inline operator std::vector<int>()
{
return x_;
}
inline operator int()
{
return x_[0];
}
std::vector<int> x_;
};
A add()
{
return A({1,2,3,4});
}
int main()
{
std::vector<int> b{add()};
}
In the code above, b will have only 1 element, which means the conversion A->int is picked over A->vector<int>. Why is that?
Is it because at the formation of initializer_list, both conversion works so it picks the one A->int?
std::vectorhas a constructor that accepts astd::initialize_list. When a class has such a constructor, that overload will always be chosen when brace initialization is used, if possible. It is possible in this case, ifadd()'s result is converted toint, so it is. If you trystd::vector<int> b(add());you will get a copy of the result ofadd()instead : https://godbolt.org/z/8TqMEfeYf