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

查看:1948
本文介绍了有一个简单的方法来将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";
      }
 }

gotcha真的是typedefed枚举,风格枚举。有人知道这个吗?

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天全站免登陆