繁体   English   中英

如何在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中如何做到这一点? (我不想引入其他依赖项,例如链接到Boost或依赖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在此处将函数“绑定”到给定变量)

暂无
暂无

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

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