枚举到C ++中的字符串11 [英] Enum to string in C++11

查看:131
本文介绍了枚举到C ++中的字符串11的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我意识到已在不止一次在SO,但是我找不到一个问题明确寻找目前的解决方案这个问题与C ++ 11,所以这里我们再次去..



我们可以使用C ++ 11方便地获取枚举的字符串值吗?



是现在(现在)C ++ 11中的任何内置功能,允许我们获得枚举类型的字符串表示形式,如

  typedef枚举{Linux,Apple,Windows} OS_type; 
OS_type myOS = Linux;

cout<<<在控制台上打印 Linux 的myOS

解决方案

C ++(和C)中通用的枚举到字符串功能的长期而不必要的缺乏是一个痛苦的。 C ++ 11没有解决这个问题,据我所知,C ++ 14也不会。

我个人使用代码生成来解决这个问题。 C预处理器是一种方式 - 您可以在这里的评论中看到一些其他答案。但实际上我更喜欢自己编写自己的代码生成专用于枚举。它可以轻松地生成 to_string(char *) from_string ostream operator< istream operator< is_valid ,以及更多的方法。这种方法可以非常灵活和强大,但它在项目中的许多枚举之间实现绝对的一致性,并且不会导致运行时费用。



使用Python的优秀mako 包,或者如果你是轻量级的话,或者如果你是依赖关系,或是CMake自己的生成代码的设施,CPP。很多方法,但都归结为同样的事情:您需要自己生成代码 - C ++不会为您(不幸的是)。


I realize this has been asked before more than once on SO but I couldn't find a question explicitly looking for a current solution to this issue with C++11, so here we go again..

Can we conveniently get the string value of an enum with C++11?

I.e. is there (now) any built-in functionality in C++11 that allows us to get a string representation of enum types as in

typedef enum {Linux, Apple, Windows} OS_type; 
OS_type myOS = Linux;

cout << myOS

that would print Linux on the console?

解决方案

The longstanding and unnecessary lack of a generic enum-to-string feature in C++ (and C) is a painful one. C++11 didn't address this, and as far as I know neither will C++14.

Personally I'd solve this problem using code generation. The C preprocessor is one way--you can see some other answers linked in the comments here for that. But really I prefer to just write my own code generation specifically for enums. It can then easily generate to_string (char*), from_string, ostream operator<<, istream operator<<, is_valid, and more methods as needed. This approach can be very flexible and powerful, yet it enforces absolute consistency across many enums in a project, and it incurs no runtime cost.

Do it using Python's excellent "mako" package, or in Lua if you're into lightweight, or the CPP if you're against dependencies, or CMake's own facilities for generating code. Lots of ways, but it all comes down to the same thing: you need to generate the code yourself--C++ won't do this for you (unfortunately).

这篇关于枚举到C ++中的字符串11的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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