c++ - 为用户定义的枚举覆盖 std::to_string 是否是为用户定义的枚举提供 to_string 的正确方法?

标签 c++ enums tostring

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 namespace std or to a namespace within namespace std 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/

相关文章:

java - 使用枚举值的成员类型声明泛型类时遇到问题

groovy - 在 Groovy 脚本中导入内部枚举

java - 在单独的行上使用 toString() 方法返回 Java 中集合的元素

java - 如何以正确的方式打印对象内容?

c# - 单步执行我的程序时,无缘无故地调用 ToString() 方法

c++ - 仅使用指针打印出数组中的所有其他字符

c++ - 一个定义规则 - 编译

C++ 错误 : base function is protected

c++ - 多重线性运算会影响整体功能更坏情况的复杂性吗?

java - 保存每个项目类型的方法