2013-04-04 38 views
0

爲什麼編譯器會在這裏抱怨?不能在初始化時轉換匿名枚舉

enum jit_ptx_type {f32=0,f64=1,u16=2,u32=3,u64=4,s16=5,s32=6,s64=7,u8=8,b16=9,b32=10,b64=11,pred=12 }; 

    // 
    // MATCHING C TYPES TO PTX TYPES 
    // 
    template<class T> struct jit_type {}; 
    template<> struct jit_type<float>   { enum { value = jit_ptx_type::f32 }; }; 
    template<> struct jit_type<double>   { enum { value = jit_ptx_type::f64 }; }; 
    template<> struct jit_type<int>    { enum { value = jit_ptx_type::s32 }; }; 
    template<> struct jit_type<bool>    { enum { value = jit_ptx_type::pred }; }; 

在後面的代碼:

some_func(float val) { 
    jit_ptx_type type = jit_type<float>::value; // compiler complains here 
    } 

編譯器消息:

error: cannot convert ‘jit_type<float>::<anonymous enum>’ to ‘jit_ptx_type’ in assignment 

很奇怪!如果我把這些行放入一個單獨的小例子文件中就行了。

+0

無法範圍的枚舉不使用限定。不過,我會使用'static constexpr int value = ...;'。 – chris 2013-04-04 21:27:58

+0

你能詳細說一下嗎? – ritter 2013-04-04 21:33:09

+0

我的意思是代替使用'jit_ptx_type :: f32',你需要'f32',或者使用'enum class'來代替。雖然它的語法無效,但它與乍看起來似乎無關。 – chris 2013-04-04 21:34:57

回答

1

我會去使外枚舉到一個範圍的枚舉:

enum class jit_ptx_type { 
    f32=0, //note the =x is unnecessary here 
    f64=1, 
    u16=2, 
    u32=3, 
    u64=4, 
    s16=5, 
    s32=6, 
    s64=7, 
    u8=8, 
    b16=9, 
    b32=10, 
    b64=11, 
    pred=12 
}; 

現在,你不必與所有這些標識符的污染周圍的範圍和需要範圍預選賽訪問值,而無與倫比的枚舉不允許這樣做。接下來,在您的課堂上,只需使用一個靜態常量成員:

template<> struct jit_type<float> { 
    static constexpr value = jit_ptx_type::f32; 
};