[英]overloading << operator on enums gives runtime error
喜歡這段代碼:
#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;
}
這會導致無限遞歸。 請記住,在這個實例中, 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;
}
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);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.