如何将模板对象存储在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()
方法。
由于将使用不同的模板参数实例化的实例存储(A<int>
,A<float>
,...)显然不能使用std::vector
并将实例或指针存储在其中。我可以想象的是将方法static
和将功能指针存储到void foo()
,例如:
void static foo();
typedef void (* fooPtr)(void);
std::vector<fooPtr>
但是,我有些感觉这不是很C 11。是否有一个不错的解决方案引入包装类或其他内容?
引入基类并使用动态铸件会引入RTTI
的依赖性,对吗?我想避免对RTTI
的依赖。
在C 11中将如何做到这一点?(我不想介绍其他依赖项,例如链接到升压或取决于RTTI
。)
感谢您的意见!
您可能只能使用虚拟方法?这也可用于C 03。
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();
如果您实际上需要一系列功能,则可以将std::function
与std::bind
std::vector<std::function<void()> vec;
A<int> a;
vec.push_back(std::bind(&A<int>::foo, &a)); //now a should live at least as long, as vec
// or vec.push_back(std::bind(&A<int>::foo, a)); - now a will be _copied_ to vec
foo
现在是一个模因函数(std::bind
'绑定'在此处给定的变量的函数)
相关文章:
- 类模板的成员功能的定义在单独的TU中完全专业化
- 升压信号2将插槽传递到成员功能以断开连接
- 多次实现成员功能
- 私有成员数据不可用于公共成员功能
- 如何避免大多数成员功能相同的代码重复
- C 成员功能
- =删除用户定义的成员功能,除了构造函数,分配运算符C 11
- C 朋友课程和朋友成员功能
- C 函数调用包装器包含类成员功能作为模板参数
- 创建类成员功能
- 成员功能C 的不同实现
- 返回类型不可知模板类成员功能
- C 11螺纹 - 非静态成员功能的使用无效 - 工作GCC 5.1.0损坏的GCC 7.3.1
- 超载类成员功能标记为const
- C 功能指针和成员功能指针
- 将非静态成员函数C 的使用无效,而将成员功能作为函数变量
- 我可以使用Priority_queue的基础容器的成员功能
- 如何子类可运行任何成员功能
- 共享类时如何隐藏成员功能文件
- 从C文件访问C 类成员功能