当我不控制源时,如何"add aliases"枚举值?

How can I "add aliases" to enum values when I don't control the source?

本文关键字:add aliases 枚举 如何 控制      更新时间:2023-10-16

(后续问题)

我正在写一个使用库的程序,库的头文件定义了

enum foo : unsigned { first_foo, second_foo };

现在,我想给foo值添加一些别名。如果我能控制库的源代码,我会写:

enum foo : unsigned { 
    first_foo,
    second_foo,
    best_foo   = first_foo,
    worst_foo  = second_foo,
    oldest_foo = first_foo,
    newest_foo = second_foo; 
};

…但我控制不了源头所以,我想写:

enum bar : foo { 
    best_foo   = first_foo,
    worst_foo  = second_foo,
    oldest_foo = first_foo,
    newest_foo = second_foo; 
};

,但在c++中无效,因为foo不是整型。如果我尝试绕过它并使用底层类型:

enum bar : std::underlying_type<foo> {  /* etc. etc. */ }

可以编译,但是-我没有得到foo类型的值,并且我得到了编译器关于barfoo比较的警告。

我可以使用static const变量:

    static const auto best_foo    = first_foo;
    static const auto worst_foo   = second_foo,
    static const auto oldest_foo  = first_foo,
    static const auto newest_foo  = second_foo; 

但是我不想冒险让它们进入文本部分,或者符号表

那么,我该怎么办呢?

您可以完全单独定义enum bar,然后重载bar和foo的一元+操作符以返回foo:

constexpr foo operator + ( bar const input )
{
    return static_cast <foo> ( input );
}
constexpr foo operator + ( foo const input )
{
    return input;
}