如何将模板对象存储在STL容器和成员功能调用中

How to store templated objects in an STL container and member function call

本文关键字:成员 功能 调用 STL 存储 对象      更新时间:2023-10-16

假设您有一个类似

的类
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::functionstd::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'绑定'在此处给定的变量的函数)