How to add element to various container depending of type using template

前端 未结 5 598
长发绾君心
长发绾君心 2021-01-22 08:04

I\'ve got rather silly question but I hope that you can help me with that.

I\'ve got class with multiple vectors, and this vectors have different storage types.

<
5条回答
  •  有刺的猬
    2021-01-22 08:51

    What if you make use of the shared BaseClass like this?? You will have to create a common interface for BaseClass, I am not sure how much B and C will differ in terms of functionality though.

    class BaseClass{
    public:
        std::string Name;
    };
    
    class B : public BaseClass{
    };
    class C : public BaseClass{
    };
    
    class A{
    public:
        std::vector> > V1;
        std::vector> > V2;
    
        template   void addElement(T Obj)
        {
    
            std::pair> AddedPair(Obj.Name, std::make_unique(Obj));
    
            if (typeid(T) == typeid(B)) 
                V1.push_back(AddedPair);
    
            else if (typeid(T) == typeid(C)) 
                V2.push_back(AddedPair);
        }  
    };
    
    int main()
    {
      A a;
      B b;
      C c;
    
      a.addElement(b) ;//-> then element b is added to vector V1
      a.addElement(c) ;//-> then element c is added to vector V2
    }
    

提交回复
热议问题