有没有一种简单的方式来将C ++枚举转换为字符串? [英] Is there a simple way to convert C++ enum to string?

查看:150
本文介绍了有没有一种简单的方式来将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);

并且这样的一个实现:

char* enum_to_string(MyEnum t){
      switch(t){
         case FOO:
            return "FOO";
         case BAR:
            return "BAR";
         default:
            return "INVALID ENUM";
      }
 }

getcha是真正的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.

推荐答案

你可能想检查 GCCXML

运行您的示例代码中的GCCXML产生:

Running GCCXML on your sample code produces:

<GCC_XML>
  <Namespace id="_1" name="::" members="_3 " mangled="_Z2::"/>
  <Namespace id="_2" name="std" context="_1" members="" mangled="_Z3std"/>
  <Enumeration id="_3" name="MyEnum" context="_1" location="f0:1" file="f0" line="1">
    <EnumValue name="FOO" init="0"/>
    <EnumValue name="BAR" init="80"/>
  </Enumeration>
  <File id="f0" name="my_enum.h"/>
</GCC_XML>

您可以使用任何您喜欢的语言来拉出Enumeration和EnumValue标签,并生成所需的代码。

You could use any language you prefer to pull out the Enumeration and EnumValue tags and generate your desired code.

这篇关于有没有一种简单的方式来将C ++枚举转换为字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆