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 Namespace std [namespace.std]
The behavior of a C++ program is undefined if it adds declarations or definitions to namespacestd
or to a namespace within namespacestd
unless otherwise specified. A program may add a template specialization for any standard library template to namespace std only if the declaration depends on a user-defined type and the specialization meets the standard library requirements for the original template and is not explicitly prohibited.
更好的解决方案是在您自己的命名空间中重载它,并调用 to_string(c)
而不是 std::to_string(c)
。这将找到正确的功能,您无需向 std
关于c++ - 为用户定义的枚举覆盖 std::to_string 是否是为用户定义的枚举提供 to_string 的正确方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17136497/