Templatized Storing Multiple Different Types In std::vector

前端 未结 2 1879
萌比男神i
萌比男神i 2021-01-24 17:46

thank you all for your time I really appreciate it.

There exists a need to store multiple variables of different types in a std::vector using a templatized fashion. To u

2条回答
  •  没有蜡笔的小新
    2021-01-24 18:15

    The vector should be:

    std::vector<_NetVar *> DataVec;
    

    or a high level pointer

    std::vector > DataVec;
    

    so that you can store instances of the child classes instead of slicing them to the base class.

    On GetData you will need to upcast the pointer retrieved from the vector.


    Edit: Adding a full blown working code

    Example working on ideone, had to fiddle with the permissions a bit.

    and the example goes with some comments added.

    #include 
    #include 
    #include 
    class _NetVar {};
    
    template  
    class NetVar : public _NetVar
    {
    private:
        VARTYPE Var;
    public:
        NetVar(VARTYPE Value)
        {
            Var = Value;
        }
    };
    

    Note that I changed NetVar<> constructor and Var attribute to be public... AddData and GetData needed to access it.

    Not sure if in your example you had some virtual methods on _NetVar (in which case the static_pointer_cast below could be a dynamic_pointer_cast)

    Related to that, you might want to veriy that the destructors for NetVar (and not only the destructors for _NetVar) are being called (checked on ideone, they work in my example because I'm using std::make_shared >(...))

    std::vector > DataVec;
    int VecPos;
    

    Added this global variables for the functions below to work.

    template  void AddData(DATATYPE AddData)
    {
        DataVec.push_back(std::make_shared >(AddData));
    }
    

    So here we create a shared_ptr with new object NetVar and push it into the vector.

    template  DATATYPE GetData()
    {
        std::shared_ptr<_NetVar> content = DataVec[VecPos];
        std::shared_ptr > Temp = std::static_pointer_cast >(content);
        ++VecPos;
    
        return Temp->Var;
    }
    

    Here, the content of the vector is std::shared_ptr<_NetVar> so that's what we get. That shared_ptr needs to be upcasted to the right kind of shared_ptr

    Now there's a concern that you must know the right type to upcast to, otherwise is undefined behaviour. If you had virtual methods you could use dynamic_pointer_cast and then perform a check for null... but that has some performance penalties

    int main() {
    
        AddData(32);
        AddData(true);
        AddData("Test");
    
        auto Var1 = GetData();
        auto Var2 = GetData();
        auto Var3 = GetData();
    
        std::cout << Var1 << std::endl;
        std::cout << Var2 << std::endl;
        std::cout << Var3 << std::endl;
        return 0;
    }
    

    Finally testing and printing the resuls.

提交回复
热议问题