重载<<枚举上的运算符给出运行时错误

时间:2016-02-28 05:56:44

标签: 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;
}

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

2 个答案:

答案 0 :(得分:8)

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

这会导致无限递归。请记住,在此实例中,编译器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;
}

答案 1 :(得分:5)

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);

}
相关问题