简体   繁体   English

C ++以任何方式将不同的模板化对象存储到同一个容器中

[英]C++ Any way to store different templated object into the same container

Is there any hack I could use to do this: 有什么黑客我可以用来做到这一点:

template <class TYPE>
class Hello
{
     TYPE _var;
};

I would like a way to store 我想要一种存储方式

Hello<int> intHello and Hello<char*> charHello

into the same Container such as a Queue / List. 进入同一个容器,如队列/列表。

No, because they are different and completely unrelated types. 不,因为它们是不同的,完全不相关的类型。

You can, however, use inheritance and smart pointers: 但是,您可以使用继承和智能指针:

class HelloBase 
{
public:
    virtual ~HelloBase(); 
}

template <class TYPE>
class Hello : public HelloBase
{
    TYPE _var;
}

std::vector<boost::shared_ptr<HelloBase> > v;

shared_ptr may be supported by your implementation either in the std::tr1 or std namespace; 您的实现可能在std::tr1std命名空间中支持shared_ptr ; you'd have to check. 你必须检查。

Yes, sort of -- but you probably don't want to. 是的,有点 - 但你可能不想。 Even though they start from the same template, Hello<int> and Hello<char *> are completely separate and unrelated types. 即使它们从相同的模板开始, Hello<int>Hello<char *>也是完全独立且不相关的类型。 A collection that includes both is heterogeneous, with all the problems that entails. 包含两者的集合是异构的,包含所有需要的问题。

If you insist on doing this anyway, to do it reasonably cleanly, you'd typically create something like a queue/list of Boost::any . 如果你坚持这样做,为了合理地干净利落,你通常会创建类似Boost::any的队列/列表。

First of all, the real question: what are you trying to achieve (at a higher level) ? 首先,真正的问题是:你想要达到的目标是什么(更高层次)?

Now, for this peculiar question there is a number of alternative. 现在,对于这个特殊的问题,有许多替代方案。 Containers cannot store heterogeneous data, so you can: 容器无法存储异构数据,因此您可以:

  • give all Hello<T> a common base class and add virtual methods, then use pointers, take care of memory ownership ( unique_ptr or boost::ptr_list would be great) 给所有Hello<T>一个公共基类并添加虚方法,然后使用指针,处理内存所有权( unique_ptrboost::ptr_list会很棒)
  • if there is a precise set of types, use boost::variant , it's statically checked so you have reasonable guarantees 如果有一组精确的类型,请使用boost::variant ,它会被静态检查,以便您有合理的保证
  • else you should consider wrapping it into a storage class which would use boost::any under the covers 否则你应该考虑将它包装到一个存储类中,它将使用boost::any

The common base class is the usual approach in this situation. 在这种情况下,通用基类是通常的方法。 If there is no reason to have polymorphism, then use preferably variant and if nothing else any . 如果没有理由,多态性,然后用最好variant ,如果没有其他any

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

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