枚举c++中成员的成员,或可选成员

enum members of members in C++, or alternative

本文关键字:成员 c++ 枚举      更新时间:2023-10-16

我想用c++创建一个enum,它的成员有成员。
我在这里有一个类似的问题,但那个问题是关于D的,而不是c++的。


在Python中,我可以这样做:
class Product(enum.Enum):
    PHOTOSHOP = "Image editor.", 0
    FIREFOX = "Web browser.", 1
    NOTEPAD = "Text editor.", 2
    def __init__(self, description, num):
        self.description = description
        self.num = num
>>> print(Product.PHOTOSHOP.description)
>>> "Image editor."

Java可以这样做:

public enum Product {
    PHOTOSHOP("Image editor.", 0),
    FIREFOX("Web browser.", 1),
    NOTEPAD("Text editor.", 2);
    private final String description;
    private final int num;
    Product(String description, int num) {
        this.description = description;
        this.num = num;
    }
}

我可以在c++中这样做吗?
如果这种效果在c++中无法实现,那么还有什么好的替代方案呢?

据我所知,在c++中不能有多组件枚举,尽管我不自称是专家。

你能做的是声明一个enum,并使用它来查找数组中的字符串。

enum Product
{
    PHOTOSHOP = 0,
    FIREFOX,
    NOTEPAD,
    // must always be last
    PRODUCT_ENUM_SIZE
};
const char* Product_Descriptions[PRODUCT_ENUM_SIZE];
Product_Descriptions[PHOTOSHOP] = "Image Editor";
Product_Descriptions[FIREFOX] = "Web Browser";
Product_Descriptions[NOTEPAD] = "Text Editor";
std::cout << "Firefox product number: " << FIREFOX << ". Description: " << Product_Descriptions[FIREFOX] << std::endl;

通过使用结构体而不是enum,您可以完成类似的操作:

struct Product
{
    static constexpr struct type {const char* const description; const int num;}
        PHOTOSHOP{"Image editor.", 0},
        FIREFOX{"Web browser.", 1},
        NOTEPAD{"Text editor.", 2};
};

不幸的是,您不能使用std::string,因为它不是"文字"类型,因此不适合在constexpr对象中使用。

另一个问题是枚举数的类型是Product::type,而不仅仅是Product,这将影响需要声明变量的任何代码。在使用内联定义的同时,条目的类型与包含它们的类型是不可能的。

我意识到它没有回答这个问题,但是一个功能完整的枚举不可避免地需要传递对单例的引用,而不仅仅是一个值(从而影响代码的空间局部性)。这不是c++的方式。

c++的方法是只在必要的时候付出代价。例如:

enum class X { ... };
char const* to_str(X x) { return lookup_value_in_static_map(x);}
X from_str(char const* v)
ostream& operator <<(ostream& out, X x) { return out << to_str(x); }

如果需要,可以通过一些简单的调整使上面的代码在编译时友好。