检查C++ 11 #defines中的类型

Col*_*ett 1 c++ typedef c++11

我想根据a的值制作预处理器定义typedef.

我们的想法是检查index_type_t并生成适当的INDEX_TYPE_GL定义.

以下内容无法正常工作.

typedef uint32_t index_type_t;

#ifdef INDEX_TYPE_GL
#undef INDEX_TYPE_GL
#endif

#if (index_type_t == uint8_t)
#define INDEX_TYPE_GL   GL_UNSIGNED_BYTE
#elif (index_type_t == uint32_t)
#define INDEX_TYPE_GL   GL_UNSIGNED_INT
#elif (index_type_t == uint16_t)
#deine INDEX_TYPE_GL    GL_UNSIGNED_SHORT
#endif
Run Code Online (Sandbox Code Playgroud)

请注意uint8_t,uint16_t并且uint32_ttypdefs其他地方是分开的,GL_UNSIGNED_BYTE等等是整数值,而不是类型.

Jar*_*d42 5

枚举风格:

template<typename T> struct IndexTypeGL {};
template<> struct IndexTypeGL<uint8_t>  { enum {value = GL_UNSIGNED_BYTE }; };
template<> struct IndexTypeGL<uint16_t> { enum {value = GL_UNSIGNED_SHORT}; };
template<> struct IndexTypeGL<uint32_t> { enum {value = GL_UNSIGNED_INT  }; };

#define INDEX_TYPE_GL  IndexTypeGL<index_type_t>::value
Run Code Online (Sandbox Code Playgroud)

"静态constexpr"风格

template<typename T> struct IndexTypeGL {};
template<> struct IndexTypeGL<uint8_t>  { static constexpr int value = GL_UNSIGNED_BYTE; };
template<> struct IndexTypeGL<uint16_t> { static constexpr int value = GL_UNSIGNED_SHORT;};
template<> struct IndexTypeGL<uint32_t> { static constexpr int value = GL_UNSIGNED_INT;  };
Run Code Online (Sandbox Code Playgroud)

  • @Manu343726:静态constexpr比静态const好.enum与const之间的胜利者似乎并不清楚. (2认同)
  • @cmbasnett`template <> struct IndexTypeGL <uint8_t> {static constexpr value = GL_UNSIGNED_BYTE; };` (2认同)