枚举上的重载<<运算符会导致运行时错误

overloading << operator on enums gives runtime error

本文关键字:lt 运行时错误 运算符 枚举 重载      更新时间:2023-10-16

就像在这段代码中一样:

#include <iostream>
enum class A {
    a,
    b
};
std::ostream& operator<<(std::ostream& os, A val)
{
        return os << val;
}

int main() {
    auto a = A::a;
    std::cout << a;
    return 0;
}

当我没有提供std::ostream& operator<<(std::ostream& os, A val)程序没有编译时,因为 A::a 没有任何功能可以配合<<。但是现在,当我已经提供了它时,它在我的终端和 ideone 上产生垃圾,它会产生运行时错误(超出时间限制)。

std::ostream& operator<<(std::ostream& os, A val) {
    return os << val;
}

这会导致无限递归。请记住,在这种情况下,编译器operator<<(os,val)确实可以看到os << val。您要做的是打印枚举的基础值。幸运的是,有一个type_trait允许您公开枚举的基础类型,然后您可以将参数强制转换为该类型并打印它。

#include <iostream>
#include <type_traits>
enum class A {
    a, b
};
std::ostream& operator<<(std::ostream& os, A val) {
    return os << static_cast<std::underlying_type<A>::type>(val);
}
int main() {
    auto a = A::a;
    std::cout << a;
}
std::ostream& operator<<(std::ostream& os, A val)
{
   return os << val; // Calls the function again.
                     // Results in infinite recursion.
}

尝试

std::ostream& operator<<(std::ostream& os, A val)
{
   return os << static_cast<int>(val);
}