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

こ雲淡風輕ζ 提交于 2019-12-12 06:47:19

问题


(Followup question to this one)

I'm writing a program that uses a library, whose header file defines

enum foo : unsigned { first_foo, second_foo };

Now, I want to add some aliases to foo values. If I were in control of the library's source, I would write:

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

... but I don't control the source. So, I would have liked to write:

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

but that is invalid C++, since foo is not an integral type. If I try to work around it and use the underlying type:

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

it compiles, but then - I don't get values of type foo, and I get compiler warnings about comparison between bar's and foo's.

I can use static const variables:

    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; 

but I don't want to risk them going into the text section, or the symbol table.

So, what should I do?


回答1:


You can define enum bar completely separately, then overload the unary + operators for both bar and foo to return foo:

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

constexpr foo operator + ( foo const input )
{
    return input;
}


来源:https://stackoverflow.com/questions/40607928/how-can-i-add-aliases-to-enum-values-when-i-dont-control-the-source

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!