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

后端 未结 3 1537
时光取名叫无心
时光取名叫无心 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 <typename T>
    class IVectorImpl : public Ivector
    {
    public:
        explicit IVectorImpl(std::vector<T> * Data) : m_Data(Data){}
        std::vector<T> * 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 <typename T>
    void setVec(std::vector<T> * vec)
    {
       Ivector * newVec = new IVectorImpl<T>(vec);
       delete myVec;
       myVec = newVec;
    }
    
    0 讨论(0)
  • 2021-01-22 00:46

    You could do this:

    class vector_container_base
    {
    public:
        ~vector_container_base() {}
    
        virtual std::size_t size() const = 0;
    };
    
    template <typename T>
    class vector_container :
        public vector_container_base
    {
    public:
        typedef std::vector<T> vector_type;
    
        std::size_t size() const
        {
            return mVector.size();
        }
    
    private:
        vector_type mVector;
    };
    

    And so on, but I doubt this is too useful in any real situation.

    0 讨论(0)
  • 2021-01-22 00:52

    The line

    std::vector* myVec
    

    is not syntactically correct. One has to specify the type of the vector elements.

    You may want to do something on the line of

    template< typename T >
    class Foo{
      private:
        std::vector<T> * myVec;
    };
    

    However, even that doesn't look nice, re-evaluating the design might be more important here.

    0 讨论(0)
提交回复
热议问题