2016-08-26 64 views
-3

讓我們考慮下面的代碼:爲什麼不允許從強類型枚舉到其基礎類型的隱式轉換?

#include <type_traits> 

enum class foo_bar : unsigned 
{ 
    foo, 
    bar, 
}; 

int main() 
{ 
    foo_bar bar = foo_bar::bar; 
    // unsigned a = bar; -- error: cannot convert ‘foo_bar’ to ‘unsigned int’ in initialization 
    unsigned a = static_cast<std::underlying_type<foo_bar>::type>(bar); 
    return 0; 
} 

爲什麼隱式轉換是不允許的?基礎類型是已知的,類型a匹配foo_bar基礎類型。隱式轉換似乎是安全的,可以在不丟失信息的情況下執行。爲什麼從語言設計的角度來看演員是必要的?

+15

因爲這就是整個觀點? – Xeo

+0

> strong typed>隱式轉換 –

+0

@Xeo:來留下相同的評論,你毆打我,它噢:) –

回答

4

N2347,與隱積分的推廣問題是,你可以比較兩個不同枚舉:

enum Color { ClrRed, ClrOrange, ClrYellow, ClrGreen, ClrBlue, ClrViolet }; 
enum Alert { CndGreen, CndYellow, CndRed }; 
Color c = ClrGreen; 
Alert a = CndGreen; 
bool armWeapons = (a >= c); // compiles but does not make sense 

要看到什麼是真的在這裏,你可以模擬枚舉類與結構:

struct A { 
    operator int() const { 
     // for simplicity, just return fixed value 
     return 1; 
    } 
}; 

struct B { 
    operator int() const { 
     return 2; 
    } 
}; 

A a; 
B b; 
int i = b; // ok 
bool x = (a < b); // yay, this compiles 

現在,正確的解決方案將是使運營商explicit

struct B { 
    explicit operator int() const { 
     return 2; 
    } 
}; 

A a; 
B b; 
bool x = (a < b); // finally does not work 
int i = b; // but now this does not work without explicit cast either 
相關問題