Storing multiple types of a templated class into a container

后端 未结 2 731
南方客
南方客 2021-01-21 13:47

If I have a class with a template:

template
class foo{
    T m_a;

    foo(T a){
        m_a = a;
    };

    ~foo(){

    };
};
相关标签:
2条回答
  • 2021-01-21 14:32

    Different instantiations of a class-template are different (from the compilers perspective completely unrelated) types, so this question applies.

    0 讨论(0)
  • 2021-01-21 14:38

    If you want e.g. std::vector<foo<T>*>, then you need to use a non-templated base class. It will need to use dynamic dispatch, so all of the public interface should be declared virtual.

    struct foo_base {
        virtual ~foo_base() {}
        virtual void something() = 0;
    };
    
    template <typename T>
    struct foo : foo_base {
        // ...
        void something() { /* do something with T */ }
    };
    

    Then your container is std::vector<foo_base*>. Another, perhaps better, way, is to use boost::variant. This limits the number of types you can store, but at the same time doesn't require base class and virtual interface.

    typedef boost::variant<foo<int>, foo<std::string>> foo_variants;
    std::vector<foo_variants> v;
    

    Third way is to use boost::any, but that will require boost::any_cast wherever you use them, and allow absolutely anything to be stored in the vector.

    std::vector<boost::any> v;
    
    0 讨论(0)
提交回复
热议问题