Modern Effective C++ Item10:
- 什麼是unscoped enum和scoped enum?
- 推薦使用scoped enum的原因…
10.1 什麼是unscoped enum? Scoped enum?
在C++11之前,使用枚舉的方式是這樣的,
enum Color { black, white, red};
auto white = flase; // error, variable already exits in this scope
枚舉中的值的作用域不是在括號內,而是和Color的作用域是一樣的。因此這些enum的成員已經泄露到了enum所在的作用域去了,官方稱之爲unscoped.
在C++11之後,與之對應的版本爲scoped enum,如下
enum class Color { black, white, red};
auto white =false; //可以的
Color c = Color::red;
因爲scoped enum通過enum class聲明,因此也叫做enum class.
10.2 推薦使用scoped enum的原因?
根據modern effective c++ item10,根據這一節可以得出,傾向於選擇scoped enum,相比於unscoped enum,有以下優點:
- 上面所描述的一點是scoped enum中枚舉中的變量不會泄露出來,從而較少對命名命名空間的污染.
- scoped enum中的成員爲強類類型,不會隱式轉換.
enum Color { black, white, red};
Color c = red;
if(c > 3.4) { cout <<“c> 3.4”<<endl;} // implicit conversion
上面的枚舉變量可以隱式轉換爲int,然後從數值類型轉換爲浮點類型,和3.4進行比較。
但是scoped enum如果需要轉換到不同的類型,需要使用cast把Color轉換爲需要的類型。
enum Color { black, white, red};
double c = static_cast<double>(Color::red);
if (c > 3.4) { cout<< “c>3.4”<<endl;} // need to cast manually