简体   繁体   English

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

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

Suppose you have a class like 假设您有一个像

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

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. 并且您想使用容器(可能是STL)“注册”(或存储)该类的实例(或指向它的指针),以便以后调用所有已注册实例的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. 由于要存储使用不同模板参数实例化的实例( A<int>A<float> ,...),因此显然不能使用std::vector并存储实例或指向它的指针。 What I can imagine is making the method static and storing function pointers to void foo() , like: 我可以想象的是使该方法static并存储指向void foo()函数指针,例如:

 void static foo();

 typedef void (* fooPtr)(void);
 std::vector<fooPtr>

But somehow I have the feeling this is not very C++11-ish. 但是不知何故,我觉得这不是C ++ 11式的。 Is there a nice solution which introduces a wrapper class or something? 有没有很好的解决方案,它引入了包装器类?

Introducing a base class and using dynamic cast would introduce dependencies on RTTI , right? 引入基类并使用动态转换会引入对RTTI依赖,对吗? I would like to avoid dependencies on RTTI . 我想避免依赖RTTI

How would one do this in C++11? 在C ++ 11中如何做到这一点? (I would not like to introduce additional dependencies like linking to Boost or depending on RTTI .) (我不想引入其他依赖项,例如链接到Boost或依赖RTTI 。)

Thanks for your opinions! 感谢您的意见!

Probably you could just use virtual methods? 也许您可以只使用虚拟方法? This works with C++03 too. 这也适用于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();

If you actually need an array of functions, you can use std::function with conjunction to std::bind 如果您实际上需要一个函数数组,则可以将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 now is a memeber function ( std::bind 'binds' the function to given variable here) foo现在是一个成员函数( std::bind在此处将函数“绑定”到给定变量)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM