如何在STL容器和成员函数调用中存储模板化对象

rit*_*ter 3 c++ templates stl member-function-pointers c++11

假设你有一个类

template<class T>
struct A {
  void foo() {
    // Need access to "T" here
    typedef typename someTrait<T>::someType T2;
  }
};
Run Code Online (Sandbox Code Playgroud)

并且您希望用容器(可能是STL)"注册"(或存储)该类的实例(或指向它的指针),以便稍后调用foo()所有已注册实例的方法.

由于要实例化用不同模板参数实例化的实例(A<int>,A<float>...)显然不能使用a std::vector并将实例或指针存储到它.我能想象的是制作方法static和存储函数指针void foo(),如:

 void static foo();

 typedef void (* fooPtr)(void);
 std::vector<fooPtr>
Run Code Online (Sandbox Code Playgroud)

但不知怎的,我觉得这不是很C++ 11-ish.是否有一个很好的解决方案,它引入了一个包装类或什么?

引入基类并使用动态转换会引入依赖关系RTTI,对吧?我想避免依赖RTTI.

如何在C++ 11中做到这一点?(我不想引入额外的依赖关系,如链接到Boost或依赖RTTI.)

谢谢你的意见!

ken*_*ytm 5

可能你只能使用虚拟方法?这也适用于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();
Run Code Online (Sandbox Code Playgroud)


Lol*_*4t0 5

如果您确实需要一组函数,则可以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
Run Code Online (Sandbox Code Playgroud)

foo现在是一个memeber函数(std::bind这里将函数'绑定'到给定变量)