是否为用户定义的枚举重写std :: to_string是否为用户定义的枚举提供to_string的正确方法?

时间:2013-06-16 18:45:34

标签: c++ enums tostring

C ++没有办法获取枚举的字符串表示。人们通过编写包含许多样板代码的自定义函数来解决这个问题  switchcase 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;

}

此解决方案有任何问题吗?

1 个答案:

答案 0 :(得分:22)

这不是“覆盖”(适用于virtual函数),并且您没有添加“专门化”(适用于模板),您添加了一个重载,它添加了一个声明和定义命名空间std的新函数和禁止使用的函数:

  

17.6.4.2.1命名空间std [namespace.std]
  如果C ++程序向名称空间std或名称空间std中的名称空间添加声明或定义,则它是未定义的,除非另有说明。只有当声明取决于用户定义的类型且专业化符合原始模板的标准库要求且未明确禁止时,程序才可以将任何标准库模板的模板特化添加到命名空间std。

更好的解决方案是在您自己的命名空间中重载它,并调用to_string(c)而不是std::to_string(c)。这将找到正确的功能,您无需向std

添加任何内容