jeudi 4 janvier 2018

Passing vector of void pointers by reference when a vector of specific type is expected

Consider the following scenario:

class A
{
    public:
        int a;
        A(int _a) : a(_a) {}
};

void Get(std::vector<A*>& vec)
{
    A* a1 = new A(5);
    A* a2 = new A(50);
    A* a3 = new A(500);
    vec.push_back(a1);
    vec.push_back(a2);
    vec.push_back(a3);
}

int main()
{
    // Scenario 1
    auto vec = std::vector<A*>();
    Get(vec);
    for(auto* v : vec)
        std::cout << v->a << std::endl;

    // Scenario 2: 
    auto vecvoid = std::vector<void*>();
    vecvoid.assign(vec.begin(), vec.end());
    for(auto* v : vecvoid)
        std::cout << static_cast<A*>(v)->a << std::endl;
    return 0;
}

In Scenario 2, is it possible to pass vecvoid directly to Get() (without overloading/modifying Get()) instead of using the two-step approach (function call followed by call to vector::assign()) as shown above?

Aucun commentaire:

Enregistrer un commentaire