将多种类型的模板类存储到容器中
如果我有一个带有模板的类:
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 ?
例如一个可以存储指向foo<的指针的向量.int >
和 foo<字符串>
同时?
For example a vector that can store a pointer to foo< int >
and foo< string >
at the same time ?
编辑更多信息
我想隐藏这个的实现:
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();
进入这个:
EventManager em;
em.listen(&Events::nameChange, &nameChangeCallback);
em.listen(&Events::healthChange, &healthChangeCallback);
em.listen(&Events::newUser, &newUserCallback);
em.processEvents();
EventManager 需要创建 EventListener 并将其存储到一个向量中,以便能够记住它们并在析构函数中删除它们.
EventManager needs to create and store EventListeners into a vector to be able to remember them and delete them in the destructor.
这就是我卡住的地方.
推荐答案
如果你想要例如std::vector<foo<T>*>
,那么你需要使用一个非模板化的基类.它需要使用动态调度,所以所有的公共接口都应该声明为virtual
.
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 */ }
};
那么你的容器就是 std::vector
.另一种可能更好的方法是使用 boost::variant
.这限制了您可以存储的类型数量,但同时不需要基类和虚拟接口.
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;
第三种方法是使用 boost::any
,但这将需要 boost::any_cast
在任何地方使用它们,并且绝对允许将任何内容存储在向量中.
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;
相关文章