初始化时不能转换匿名枚举

cannot convert anonymous enum in initialization

本文关键字:枚举 转换 不能 初始化      更新时间:2023-10-16

为什么编译器在这里抱怨?

  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

真奇怪!如果我把这些行放到一个单独的小示例文件中,它可以工作。

我倾向于让外部枚举变成一个有作用域的枚举:

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; 
};