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

标签 c++ containers generic-programming

我正在尝试创建一个通用容器,它可以存储 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();
  while(it != end){
    it->foo();
    ++it;
  }
}

最佳答案

最通用的方法是为 Wrapper 创建一个基类,比如 BaseWrapper,然后在 BaseWrapper 上定义纯虚函数,然后在每个 Wrapper 类上实现这些函数。通过特化,每个 Wrapper,Wrapper,都可以有自己的实现。完成此操作后,您可以使用指向基本类型的智能指针容器,并在闲暇时使用它。

有一些可能的捷径。例如,在您示例中的简单情况下,我建议使用 std::function。辅助函数有助于执行此操作。请注意,这仅在只有一种方法被调用时才有效。我还建议让您的包装器直接定义 operator(),这样您就不必使用绑定(bind)。

template<T>
std::function<void()> wrap(const T& x)
{
   return std::bind(&Wrapper<T>::foo, Wrapper<T>(x));
}

int main(){
  X x;
  Y y;

  std::vector<std::function<void()> > 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(wrap(x));
  generic_container.push_back(wrap(y));

  auto it =  generic_container.begin();
  auto end =  generic_container.end();
  while(it != end){
    (*it)();
    ++it;
  }
}

编辑:

我讨论的是非模板化基础,您可以从中派生所有模板化包装器。这允许您调用您预定义的方法(并且必须由包装器实现),而无需知道涉及的特定包装器类型。

class Base
{
  public:
   virtual ~Base() {};
   virtual void foo() = 0;
};

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

int main(){
  X x;
  Y y;

  std::vector<std::shared_ptr<Base> > 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(std::make_shared<Wrapper<X>>(x));
  generic_container.push_back(std::make_shared<Wrapper<Y>>(y));

  auto it =  generic_container.begin();
  auto end =  generic_container.end();
  while(it != end){
    it->foo();
    ++it;
  }
}

关于c++ - 用于在 C++ 中存储特定模板对象的通用容器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12994416/

相关文章:

c++ - 为什么我不能重新分配以前在 C++ 堆栈上分配的变量( 'Frame' 的复制赋值运算符被隐式删除)?

c++ - 继承 Shell 类以供容器使用

haskell - 使用 Data 和 Typeable 获取构造函数的参数类型

c++ - 重载 [] 和 , c++11

c++ - 匿名聚合规则

c++ - 为什么这个指针在 Visual Studio 2012 Professional 中仍然有效?

containers - 无法设置LVM时的快照选项

containers - 如何在 GKE 上使用 Docker Hub 私有(private)存储库?

C++如何用模板特化或其他方式实现?

c++ - 在泛型函数中使用仿函数