小编bis*_*nda的帖子

在 C++ 中存储特定模板对象的通用容器

我正在尝试创建一个通用容器,它可以存储 Wrapper< T> 类型的异构对象,其中 T 可以是任何用户定义的类型。我已经看到了 boost::any 和其他解决方案,但我不能在不重铸的情况下调用函数 foo()(我不知道要重铸哪种类型,关于 T 的信息丢失了。)它回到原始类型。

我怎样才能合理地实现一个通用容器/使用现有的通用容器来实现这一点?

template <typename T>
class Wrapper{
public:
  Wrapper(const T& a):o(a){};
  Wrapper(){};
  //public methods
  void foo(){
     //do stuff
  };
private:
 T o;
};

class X{};
class Y{};

int main(){
  X x;
  Y y;

  A_GENERIC_CONTAINER generic_container;
  // A_GENERIC_CONTAINER should be able to store
  // any number of heterogeneous objects of type Wrapper<T>
  // where T can be any user defined type.

  generic_container.push_back(x);
  generic_container.push_back(y);

  auto it =  generic_container.begin();
  auto end =  generic_container.end(); …
Run Code Online (Sandbox Code Playgroud)

c++ containers generic-programming

3
推荐指数
1
解决办法
3389
查看次数

标签 统计

c++ ×1

containers ×1

generic-programming ×1