-1

(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?

Community
  • 1
  • 1
einpoklum
  • 118,144
  • 57
  • 340
  • 684
  • Is making `bar` a strict superset of `foo` a reasonable solution for you? – TartanLlama Nov 15 '16 at 10:57
  • @TartanLlama: That's not possible. the library has determined which values a `foo` may have, and my `bar`s are, specifically, `foo`'s which need to interact with code expecting `foo`s. – einpoklum Nov 15 '16 at 15:38

1 Answers1

0

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;
}
KevinZ
  • 3,036
  • 1
  • 18
  • 26