简体   繁体   English

如何在C ++中实现Swift枚举关联的值?

[英]How can I implement Swift enum associated values in C++?

In Swift I'm implementing a state machine where the current state is represented by an enum value. 在Swift中,我实现了一个状态机,其中当前状态由枚举值表示。 I associate extra data of varying types with each enum value. 我将不同类型的额外数据与每个枚举值相关联。 Is there a way to do this in C++? 有没有办法在C ++中做到这一点? I can only think of using inheritance of some State class, but I would later have to use some kind of reflection and cast the State objects to get the extra associated data. 我只能想到使用某些State类的继承,但是以后我将不得不使用某种反射并将State对象强制转换以获取额外的关联数据。

One way is to have a base class representing the enum, and subclasses for each of the cases (each class having variables for the associated value for that case). 一种方法是具有一个代表枚举的基类,以及每种情况的子类(每个类都具有该情况下关联值的变量)。 The base class should be polymorphic (have at least one virtual method; probably a virtual destructor), so that the "enum" can be deconstructed by testing it against each case using dynamic_cast . 基类应该是多态的(具有至少一个虚拟方法;可能是虚拟析构函数),以便可以通过使用dynamic_cast针对每种情况对其进行测试来解构“枚举”。

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

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