Storing templated objects in a vector (Storing Class, Class in a single vector)

前端 未结 2 1018
情书的邮戳
情书的邮戳 2021-01-20 22:25

There is a templated class, let it be

template class A { std::vector data; };

The problem I am facing here is,

2条回答
  •  日久生厌
    2021-01-20 23:05

    std::any is the modern c++17 solution. Specifically, you should use

    A a;
    a.data.push_back(0);
    
    // fill refernces...
    std::vector refernces; 
    refernces.push_back(&a.data[0]);
    
    // check which type is active.
    if(int** iPtr = std::any_cast(&references[0]); iPtr != nullptr)
    {
         // its an int*
         int& i = **iPtr;
         // do something with i.
    }
    

    These pointers can point into the A::data and A::data vectors.

    For a complete reference, see here https://en.cppreference.com/w/cpp/utility/any.

提交回复
热议问题