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).
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With