強類型枚舉
-
在傳統 C++中,枚舉類型並非類型安全,枚舉類型會被視作整數,則會讓兩種完全不同的枚舉類型可以進行直接的比較(雖然編譯器給出了檢查,但並非所有),甚至枚舉類型的枚舉值名字不能相同,這不是我們希望看到的結果。
-
C++11 引入了枚舉類(enumaration class),並使用
enum class
的語法進行聲明:enum class new_enum : unsigned int { value1, value2, value3 = 100, value4 = 100 }; int main() { return 0; }
-
這樣定義的枚舉實現了類型安全,首先他不能夠被隱式的轉換爲整數,同時也不能夠將其與整數數字進行比較,更不可能對不同的枚舉類型的枚舉值進行比較。但相同枚舉值之間如果指定的值相同,那麼可以進行比較
enum class new_enum : unsigned int { value1, value2, value3 = 100, value4 = 100 }; int main() { if (new_enum::value3 == new_enum::value4) { // 會輸出 cout << "new_enum::value3 == new_enum::value4" <<endl; } return 0; }
-
在這個語法中,枚舉類型後面使用了冒號及類型關鍵字來指定枚舉中枚舉值的類型,這使得我們能夠爲枚舉賦值(未指定時將默認使用 int)。而我們希望獲得枚舉值的值時,將必須顯式的進行類型轉換,不過可以通過重載
<<
這個算符來進行輸出,可以收藏下面這個代碼段:template<typename T> ostream& operator<<(typename enable_if<std::is_enum<T>::value, std::ostream>::type& stream, const T& e) { return stream << static_cast<typename std::underlying_type<T>::type>(e); }
-
下面的代碼將能夠被編譯:
std::cout << new_enum::value3 << std::endl;
完整代碼:
#include <bits/stdc++.h> using namespace std; enum class new_enum : unsigned int { value1, value2, value3 = 100, value4 = 100 }; template<typename T> ostream& operator<<(typename enable_if<std::is_enum<T>::value, std::ostream>::type& stream, const T& e) { return stream << static_cast<typename std::underlying_type<T>::type>(e); } int main() { cout << new_enum::value3 << endl; return 0; }