在枚举上重载<<运算符会产生运行时错误

hg_*_*git 2 c++ enums

喜欢这段代码:

#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;
}
Run Code Online (Sandbox Code Playgroud)

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

Tim*_*Tim 8

std::ostream& operator<<(std::ostream& os, A val) {
    return os << val;
}
Run Code Online (Sandbox Code Playgroud)

这会导致无限递归.请记住,在这个实例中os << val,编译器确实可以看到operator<<(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;
}
Run Code Online (Sandbox Code Playgroud)

  • 这是纯粹的编译时间. (3认同)

R S*_*ahu 5

std::ostream& operator<<(std::ostream& os, A val)
{
   return os << val; // Calls the function again.
                     // Results in infinite recursion.
}
Run Code Online (Sandbox Code Playgroud)

尝试

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

}
Run Code Online (Sandbox Code Playgroud)