如何在C ++中"ToString()"枚举? [英] How do I 'ToString()' an enum in C++?
问题描述
如何在C ++中"ToString()"枚举?
How do I 'ToString()' an enum in C++?
在Java和C#中,我只会调用ToString.
In Java and C# I would just call ToString.
enum Colours
{
Red =0,
Green=1,
Blue=2
};
我需要创建一个字符串,例如:"Invalid color'"+颜色+"已选中."
I need to create a string like: "Invalid colour '" + colour + "' selected."
推荐答案
虽然这通常是通过开关完成的,但我更喜欢数组:
While this is commonly done through switches, I prefer arrays:
#include <iostream>
namespace foo {
enum Colors { BLUE = 0, RED, GREEN, SIZE_OF_ENUM };
static const char* ColorNames[] = { "blue", "red", "green" };
// statically check that the size of ColorNames fits the number of Colors
static_assert(sizeof(foo::ColorNames)/sizeof(char*) == foo::SIZE_OF_ENUM
, "sizes dont match");
} // foo
int main()
{
std::cout << foo::ColorNames[foo::BLUE] << std::endl;
return 0;
}
显式数组大小具有产生编译时间的好处如果枚举的大小发生变化,则会出错,而您忘记添加适当的字符串.
The explicit array size has the benefit of generating a compile time error should the size of the enum change and you forget to add the appropriate string.
或者,在Boost保管库中还有Boost.Enum.图书馆尚未正式发布,但相当稳定,可以提供你要.我不会推荐给新手.
Alternatively, there is Boost.Enum in the Boost vault. The library hasn't been officially released but is quite stable and provides what you want. I wouldn't recommend it to a novice though.
这篇关于如何在C ++中"ToString()"枚举?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!