Why is the conversion to int picked over the conversion to vector<int>

52 Views Asked by At
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?

1

There are 1 best solutions below

0
François Andrieux On

std::vector has a constructor that accepts a std::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, if add()'s result is converted to int, so it is. If you try std::vector<int> b(add()); you will get a copy of the result of add() instead : https://godbolt.org/z/8TqMEfeYf