C++ 没有办法获取枚举的字符串表示形式。人们通过编写包含大量样板代码的自定义函数来解决这个问题
switch
with case XYZ return "XYZ";
当然,这需要枚举的用户知道自定义函数的名称。
所以我想我可以添加一个专业std::to_string
使用户能够使用to_string
在我的枚举上。像这样的事情:
//
#include <iostream>
#include <string>
#include <cassert>
#define TEST
class Car
{
public:
enum class Color
{
Red,
Blue,
White
};
};
#ifdef TEST
#include <string>
namespace std
{
std::string to_string (Car::Color c)
{
switch (c)
{
case Car::Color::Red:
return "Red";
case Car::Color::Blue:
return "Blue";
case Car::Color::White:
return "White";
default:
{
assert(0);
return "";
}
}
}
}
#endif
int main()
{
std::cout << std::to_string(Car::Color::White) << std::endl;
}
这个解决方案有什么问题吗?
这不是“压倒一切”(适用于virtual
函数),并且您还没有添加“专业化”(适用于模板),您添加了一个重载,它将新函数的声明和定义添加到命名空间std
这是被禁止的:
17.6.4.2.1 命名空间 std [namespace.std]
如果 C++ 程序向命名空间添加声明或定义,则其行为是未定义的std
或命名空间内的命名空间std
除非另有规定。仅当声明依赖于用户定义类型并且专门化满足原始模板的标准库要求且未明确禁止时,程序才可以将任何标准库模板的模板专门化添加到命名空间 std。
更好的解决方案是在您自己的名称空间中重载它,然后调用to_string(c)
代替std::to_string(c)
。这将找到正确的功能,并且您不需要添加任何内容std
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)