Is there a simple way to convert C++ enum to string?(有没有一种简单的方法可以将 C++ 枚举转换为字符串?)
问题描述
假设我们有一些命名的枚举:
Suppose we have some named enums:
enum MyEnum {
FOO,
BAR = 0x50
};
我用谷歌搜索的是一个脚本(任何语言),它扫描我项目中的所有标题并生成一个每个枚举一个函数的标题.
What I googled for is a script (any language) that scans all the headers in my project and generates a header with one function per enum.
char* enum_to_string(MyEnum t);
还有一个类似这样的实现:
And a implementation with something like this:
char* enum_to_string(MyEnum t){
switch(t){
case FOO:
return "FOO";
case BAR:
return "BAR";
default:
return "INVALID ENUM";
}
}
问题在于 typedefed 枚举和未命名的 C 风格枚举.有人对此有所了解吗?
The gotcha is really with typedefed enums, and unnamed C style enums. Does anybody know something for this?
该解决方案不应修改我的源代码,生成的函数除外.枚举位于 API 中,因此使用目前提出的解决方案不是一种选择.
The solution should not modify my source, except for the generated functions. The enums are in an API, so using the solutions proposed until now is just not an option.
推荐答案
@hydroo: 没有额外的文件:
@hydroo: Without the extra file:
#define SOME_ENUM(DO)
DO(Foo)
DO(Bar)
DO(Baz)
#define MAKE_ENUM(VAR) VAR,
enum MetaSyntacticVariable{
SOME_ENUM(MAKE_ENUM)
};
#define MAKE_STRINGS(VAR) #VAR,
const char* const MetaSyntacticVariableNames[] = {
SOME_ENUM(MAKE_STRINGS)
};
这篇关于有没有一种简单的方法可以将 C++ 枚举转换为字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:有没有一种简单的方法可以将 C++ 枚举转换为字符


基础教程推荐
- C++ 标准:取消引用 NULL 指针以获取引用? 2021-01-01
- C++,'if' 表达式中的变量声明 2021-01-01
- C++ 程序在执行 std::string 分配时总是崩溃 2022-01-01
- 运算符重载的基本规则和习语是什么? 2022-10-31
- 调用std::Package_TASK::Get_Future()时可能出现争用情况 2022-12-17
- 如何定义双括号/双迭代器运算符,类似于向量的向量? 2022-01-01
- 如何在 C++ 中处理或避免堆栈溢出 2022-01-01
- 设计字符串本地化的最佳方法 2022-01-01
- 什么是T&&(双与号)在 C++11 中是什么意思? 2022-11-04
- 您如何将 CreateThread 用于属于类成员的函数? 2021-01-01