我如何“添加别名”当我不控制源时枚举值? [英] How can I "add aliases" to enum values when I don't control the source?
问题描述
(这一个的后续问题)
我'编写一个程序,使用一个库,其头文件定义
枚举foo:unsigned {first_foo,second_foo};
现在,我想添加一些别名到 foo
值。如果我是图书馆的来源,我会写:
枚举foo:unsigned {
first_foo,
second_foo,
best_foo = first_foo,
worst_foo = second_foo,
oldest_foo = first_foo,
newest_foo = second_foo;
};
...但我不控制源。所以,我想写:
枚举吧:foo {
best_foo = first_foo,
worst_foo = second_foo,
oldest_foo = first_foo,
newest_foo = second_foo;
};
但这是无效的C ++,因为foo不是一个整体类型。如果我试图解决它,并使用底层类型:
枚举栏:std ::底层类型< foo> {/ *等等* /}
它编译,但是 - 我不会值类型为foo,并且我收到关于 bar
和 foo
之间的比较的编译器警告。
我可以使用 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;
但我不想冒险进入文本部分或符号表。 / p>
那么我该怎么办?
code>枚举栏完全分开,然后重载一个$ $ $ $ $ $ $ $ $ $ $ $ $ $ $
constexpr foo operator +(bar const input)
{
return static_cast< foo> (输入);
}
constexpr foo operator +(foo const input)
{
return input;
}
(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?
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;
}
这篇关于我如何“添加别名”当我不控制源时枚举值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!