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

前端 未结 5 600
长发绾君心
长发绾君心 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:56

    Instead of having

    template   void addElement(T Obj);
    

    Just overload the function instead. That would give you

    void addElement(const B& Obj)
    {
        V1.push_back({Obj.Name, Obj});
    }
    
    void addElement(const C& Obj)
    {
        V2.push_back({Obj.Name, Obj});
    }
    

    This saves you all the syntax of specializing the template or needing C++17 and if constexpr to make the decision at compile time.


    The reason

    template   void addElement(T Obj){
    std::pair AddedPair(Obj.Name, Obj);
    
        if (typeid(T) == typeid(B)) 
            V1.push_back(AddedPair);
    
        if (typeid(T) == typeid(C)) 
            V2.push_back(AddedPair);
    
    }
    

    Doesn't work is the code in each if block needs to be valid (even if it could never be reached), but it can't be because you would be adding a different type into the vectors. if constexpr helps but I find overloading is just as much typing and makes the code non-backwards compatible.

    That means you would either have to specialize the template like

    template   void addElement(T Obj);
    
    template <>  void addElement(B Obj)
    {
        V1.push_back({Obj.Name, Obj});
    }   
    template <>  void addElement(C Obj)
    {
        V1.push_back({Obj.Name, Obj});
    }
    

    or using if constexpr:

    template   void addElement(T Obj){
    std::pair AddedPair(Obj.Name, Obj);
    
        if constexpr(std::is_same_v) 
            V1.push_back(AddedPair);
    
        if constexpr(std::is_same_v) 
            V2.push_back(AddedPair);
    
    }       
    

提交回复
热议问题