Search code examples
c++c++11visual-c++stdvectorimplicit-conversion

How to implicitly convert a std::vector of one type to another


Is it possible to convert a vector of one type to another implicitly?

i.e some way to make this code work (obviously this is a simplified problem of what I am trying to do)

std::vector<int> intVec{1};

std::vector<double> doubleVec = intVec;
std::vector<double> doubleVec2;
doubleVec2 = intVec;

Solution

  • No, there is no conversion (implicit or otherwise) between different vector types.

    You could initialise it from an iterator range:

    std::vector<double> doubleVec(intVec.begin(), intVec.end());
    

    perhaps wrapping this in a function:

    template <typename To, typename From>
    To container_cast(From && from) {
        using std::begin; using std::end; // Koenig lookup enabled
        return To(begin(from), end(from));
    }
    
    auto doubleVec = container_cast<std::vector<double>>(intVec);