简体   繁体   English

非模板化容器,可以容纳任何东西

[英]Non-templated container that can hold anything

I have a small framework for working with threads. 我有一个用于处理线程的小框架。 The main part is an object that is basically a mutex controlled std::queue that one thread pushes onto, and the other thread pops from. 主要部分是一个对象,它基本上是一个互斥控制的std::queue ,一个线程推入,另一个线程弹出。

This class cannot be templated, because the types of objects can vary in a single run. 此类不能模板化,因为对象类型可以在一次运行中变化。 Currently, I created a dumb class: 目前,我创建了一个哑类:

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

Any object that is to flow from thread to thread via this class must inherit from Object as it is what the std::queue holds. 通过此类从线程流向线程的任何对象都必须从Object继承,因为它是std::queue所持有的。 This works well, but I imagine there must be a better approach as this approach requires inheritance and many calls to dynamic_cast . 这很好用,但我想必须有一个更好的方法,因为这种方法需要继承和许多调用dynamic_cast Any ideas? 有任何想法吗?

EDIT The pointers in this case are also smart pointers, so type information is important to be maintained. 编辑这种情况下的指针也是智能指针,因此类型信息对于维护很重要。

Use std::queue< boost::any >. 使用std :: queue < boost :: any >。 It will hold objects of any type. 它将保存任何类型的对象。

And to get the object, you've to use a special cast function provided by boost itself: 要获得该对象,您必须使用boost本身提供的特殊强制转换函数:

Use a void* in your container for a "pointer to unknown type" (or const void* if the objects are immutable). 在容器中使用void*作为“指向未知类型的指针”(如果对象是不可变的,则使用const void* )。 It still requires casting (and therefore type information from some other side channel), but you really don't have any other options if you want to avoid templates and inheritance. 它仍然需要转换(因此来自其他一些通道的类型信息),但如果你想避免模板和继承,你真的没有任何其他选项。

如果你想更加类型安全,你可能想要研究boost :: any

The question is how the types can vary. 问题是类型如何变化。 You certainly have to have some constraints on what goes into the container. 您当然必须对容器中的内容有一些限制。 Why are the objects put into the container? 为什么将物品放入容器中? Based on this, you should be able to design are reasonable abstract base class which would allow virtual functions to be used for the dispatching, rather than deriving from an artificial Object with no interface. 基于此,您应该能够设计合理的抽象基类,它允许将虚函数用于调度,而不是从没有接口的人工Object派生。 (Depending on the purpose of the container is, some variant of the visitor pattern may be necessary. Thus, for example, a message queue might contain a virtual function processMessage( Base* ) , whose concrete implementations do nothing but call different member functions of Base .) (根据容器的用途,访问者模式的某些变体可能是必需的。因此,例如,消息队列可能包含虚函数processMessage( Base* ) ,其具体实现除了调用不同的成员函数之外什么也不做。 Base 。)

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

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