Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
175 views
in Technique[技术] by (71.8m points)

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...