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

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

    This may be a use case for a Tagged Tuple library. It makes it possible to index containers by associated type. So code dealing with dozens of similar vector> V1; fields becomes generic:

    #include 
    
    #include 
    #include 
    #include 
    #include 
    
    class BaseClass{::std::string Name;};
    class B : public BaseClass{};
    class C : public BaseClass{};
    
    class A
    {
        public: template using
        t_Vector = ::std::vector<::std::pair<::std::string, x_Item>>;
    
        public: using
        t_Vectors = ::n_vtt::n_container::t_TaggedTuple
         value type mapping
            B, t_Vector
        ,   C, t_Vector
        >;
    
        private: t_Vectors m_vectors;
    
        public: template void
        Add_Item(x_Item && item)
        {
            m_vectors
                // invoke either Get_MutableItem or Get_MutableItem
                .Get_MutableItem<::std::remove_reference_t<::std::remove_cv_t>>()
                // add item into corresponding std::vector
                .emplace_back(::std::string{}, ::std::forward(item));
        }
    };
    
    int main()
    {
        A a;
        a.Add_Item(B{});
        C c{};
        a.Add_Item(c);
        return 0;
    }
    

提交回复
热议问题