如何在STL容器中存储模板对象和成员函数调用 [英] How to store templated objects in an STL container and member function call
问题描述
假设您有一个类
template<class T>
struct A {
void foo() {
// Need access to "T" here
typedef typename someTrait<T>::someType T2;
}
};
,并且你想注册(或存储)类的实例它)与一个容器(可能是STL),以便稍后调用所有注册实例的 foo()
方法。
and you would like to "register" (or store) instances of the class (or a pointers to it) with a container (probably STL) for later calling the foo()
method of all registered instances.
因为要存储用不同模板参数实例化的实例( A
A
,.. 。)显然,不能使用 std :: vector
并存储实例或指针。我可以想象的是使方法 static
并存储函数指针 void foo()
,如:
Since instances instantiated with different template parameters are to be stored (A<int>
, A<float>
, ...) obviously one can't use a std::vector
and store the instances or pointers to it. What I can imagine is making the method static
and storing function pointers to void foo()
, like:
void static foo();
typedef void (* fooPtr)(void);
std::vector<fooPtr>
但是不知怎的,我觉得这不是很C ++ 11-ish。是否有一个很好的解决方案,引入一个包装类或者什么?
But somehow I have the feeling this is not very C++11-ish. Is there a nice solution which introduces a wrapper class or something?
引入基类并使用动态转换将引入依赖关系 RTTI
,对不对?我想避免对 RTTI
的依赖。
Introducing a base class and using dynamic cast would introduce dependencies on RTTI
, right? I would like to avoid dependencies on RTTI
.
在C ++ 11中如何做? (我不想引入其他依赖关系,如链接到Boost或依赖于 RTTI
。)
How would one do this in C++11? (I would not like to introduce additional dependencies like linking to Boost or depending on RTTI
.)
意见!
推荐答案
可能你只能使用虚拟方法?这也适用于C ++ 03。
Probably you could just use virtual methods? This works with C++03 too.
struct ABase {
virtual void foo() = 0;
};
template<class T>
struct A : ABase {
virtual void foo() override {
// Access to "T" here
}
};
...
std::vector<std::unique_ptr<ABase>> vec;
vec.emplace_back(new A<int>());
vec.emplace_back(new A<float>());
for (auto& p_a : vec)
p_a->foo();
这篇关于如何在STL容器中存储模板对象和成员函数调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!