How can I “add aliases” to enum values when I don&

2019-09-20 19:58发布

问题:

(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;
}