Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

overloading << operator on enums gives runtime error

Tags:

c++

enums

Like in this code :

#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;
}

When I did not provide std::ostream& operator<<(std::ostream& os, A val) the program didn't compile because A::a didn't have any function to go with <<. But now when I've already provided it, it produces garbage in my terminal and on ideone, it produces a runtime error (time limit exceeded).

like image 788
hg_git Avatar asked May 15 '26 01:05

hg_git


1 Answers

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

This causes infinite recursion. Remember that os << val is really seen to the compiler operator<<(os,val) in this instance. What you want to do is print the underlying value of the enum. Fortunately, there is a type_trait that allows you to expose the underlying type of the enum and then you can cast the parameter to that type and print it.

#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;
}
like image 137
Tim Avatar answered May 17 '26 14:05

Tim



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!