Storing multiple types of a templated class into a container

你说的曾经没有我的故事 提交于 2019-12-02 13:35:02

问题


If I have a class with a template:

template<typename T>
class foo{
    T m_a;

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

    ~foo(){

    };
};

Is there a way to store multiple variation of it ?

For example a vector that can store a pointer to foo< int > and foo< string > at the same time ?

Edit more info

I want to hide the implementation of this :

EventListener<string> ev1;
EventListener<int, int> ev2;
EventListener<int, string, double> ev3;

ev1(&Events::nameChange, &nameChangeCallback);
ev2(&Events::healthChange, &healthChangeCallback);
ev3(&Events::newUser, &newUserCallback);

ev1.processEvents();
ev2.processEvents();
ev3.processEvents();

into this:

EventManager em;
em.listen(&Events::nameChange, &nameChangeCallback);
em.listen(&Events::healthChange, &healthChangeCallback);
em.listen(&Events::newUser, &newUserCallback);
em.processEvents();

EventManager needs to create and store EventListeners into a vector to be able to remember them and delete them in the destructor.

That's where I'm stuck.


回答1:


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;



回答2:


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



来源:https://stackoverflow.com/questions/8081221/storing-multiple-types-of-a-templated-class-into-a-container

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!