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

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

    You might use "generic getter" for your vector:

    class A
    {
    public:
    
        template 
        std::vector>& getVector() {
            auto vectors = std::tie(V1, V2);
            return std::get>&>(vectors);
        }
    
        template 
        void addElement(T Obj) {
            getVector().emplace_back(Obj.Name, Obj);
        }
    
        std::vector> V1;
        std::vector> V2;
    };
    

    Changing your member might make sense to have std::tuple directly. and you might want to templatize the whole class:

    template 
    class A_Impl
    {
    private:
        template 
        decltype(auto) getVector() const {
            return std::get>>(Vs);
        }
        template 
        decltype(auto) getVector() {
            return std::get>>(Vs);
        }
    public:
    
        template 
        void addElement(T Obj) {
            getVector().emplace_back(Obj.Name, Obj);
        }
    private:
        std::tuple>...> Vs;
    };
    
    using A = A_Impl;
    

提交回复
热议问题