解析枚举类变量名称字符串
考虑一下,我有以下 enum
类:
enum class TestEnum
{
None = 0,
Foo,
Bar
};
我想指定 ostream operator(<<<)因此,我可以写:
std::cout << "This is " << TestEnum::Foo;
并获取以下输出这是foo
。
我的问题是:
是否有枚举“ name Specifier ”存储的地方? (即枚举类
testEnum,它是 none
, foo
and bar
))指定 Ostream
操作员的函数(或最多函数模板)的 testEnum
喜欢:
std::ostream& operator<< ( std::ostream& os, TestEnum aEnum ) {
return std::string( aEnum.name() );
}
到目前为止,我这样做了:
std::ostream& operator<< ( std::ostream& os, TestEnum aEnum ) {
switch( aEnum )
{
case TestEnum::Foo:
os << "Foo";
break;
case TestEnum::Bar:
os << "Bar"
break;
}
return os;
}
我已经使用看到了一些解决方案Boost
库,但我希望这次不使用它。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不,但是一个选项是使用
std :: map&lt; testEnum,std :: string&gt;
如下所示:demo
No, but one option is to use
std::map<TestEnum, std::string>
as shown below:Demo
不,名称在任何地方都没有保存。如果需要,需要(不幸的是)对它们进行映射。
如果
enum
值可以用于数组索引(例如OP的情况),则可以使用std :: string_view
的数组进行映射(必需 c ++ 17 或以后,否则,否则std :: String
s)。数组的使用使以下解决方案轻巧和O(1)查找。
请参阅演示
No, the names are not saved anywhere. If required, one needs to (unfortunately) make a mapping of them.
If the
enum
values can be used for array indexing (like OP's case) one might can make a mapping using array ofstd::string_view
(required c++17 or later, otherwise array ofstd::string
s).The usage of array, makes the following solution lightweight and O(1) look-up.
See a demo