pointer to std::vector of arbitrary type (or any other templated class)

后端 未结 3 1538
时光取名叫无心
时光取名叫无心 2021-01-22 00:13

let\'s say i want to have a member variable for a pointer to std::vector but i do not want to specify what type of variable it stores. I want to access only those functions that

3条回答
  •  春和景丽
    2021-01-22 00:45

    You are almost at the answer. Instead of making std::vector inherit from Ivector, create a new class:

    template 
    class IVectorImpl : public Ivector
    {
    public:
        explicit IVectorImpl(std::vector * Data) : m_Data(Data){}
        std::vector * m_Data;
     ...
         virtual int size() const {return m_Data->size();}
      // Implement all the Ivector functions here to call the respective functions off of m_Data
    };
    

    Now have your Foo class keep a pointer to Ivector instead of std::vector.

    Make Foo::setVec templated

    template 
    void setVec(std::vector * vec)
    {
       Ivector * newVec = new IVectorImpl(vec);
       delete myVec;
       myVec = newVec;
    }
    

提交回复
热议问题