2013-04-04 59 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; 
};