是否覆盖std :: to_string为用户定义的枚举提供给用户定义的枚举的to_string的正确方法? [英] Is overriding std::to_string for user defined enums the proper way to provide to_string for user defined enums?
问题描述
C ++没有办法获取枚举的字符串表示形式。人们通过编写包含很多样板代码的自定义函数来解决这个问题。
开关
与 case XYZ返回XYZ ;
C++ doesn't have a way to get the string representation of an enum. People get around this by writing custom functions that contain a lot of boilerplate code aka
switch
with case XYZ return "XYZ";
这当然要求枚举用户知道自定义函数的名称。
That of course requires users of the enum to know the name of the custom function.
所以我想我可以添加一个专门的 std :: to_string
,以使用户使用 to_string
我的枚举。这样的一个例子:
So I thought I could just add a specialization to std::to_string
to enable a user to use to_string
on my enums. Something like this:
//
#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;
}
此解决方案是否有任何问题?
Are there any problems with this solution?
推荐答案
这不是覆盖(适用于 virtual
函数),而你避风港没有添加一个专业化(适用于模板),您已经添加了一个重载,它向命名空间 std
添加了一个新功能的声明和定义,并且被禁止:
That's not "overriding" (which applies to virtual
functions), and you haven't added a "specialization" (which applies to templates), you've added an overload, which adds a declaration and definition of a new function to namespace std
and that's forbidden:
17.6.4.2.1命名空间std [namespace.std]
如果向命名空间std
或命名空间std
中的命名空间添加声明或定义,则C ++程序的行为是未定义的,除非否则指定。只有声明取决于用户定义的类型,并且专业化符合原始模板的标准库要求并且不被明确禁止,程序可以将标准库模板的模板专门化添加到命名空间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
A better solution would be to overload it in your own namespace, and call to_string(c)
instead of std::to_string(c)
. That will find the right function and you don't need to add anything to std
这篇关于是否覆盖std :: to_string为用户定义的枚举提供给用户定义的枚举的to_string的正确方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!