【问题标题】:Checking types in C++11 #defines [duplicate]检查C ++ 11中的类型#defines [重复]
【发布时间】:2013-08-19 11:08:55
【问题描述】:

我想根据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

请注意,uint8_tuint16_tuint32_t 在其他地方是独立的 typdefsGL_UNSIGNED_BYTE 等是整数值,而不是类型。

【问题讨论】:

  • 不完全是,GL_UNSIGNED_BYTE 等的值是整数。
  • 您不能以这种方式使用#ifs,因为预处理器不知道 typedefs 或任何其他 C++ 构造。你可以做的是有一个 typedef 或一个 const 值取决于 index_type_t 的实际类型。
  • 我该怎么做?
  • Jarod42 刚刚回答 :-)

标签: c++ c++11 typedef


【解决方案1】:

枚举样式:

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

“静态常量”样式

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

【讨论】:

  • 天才之笔,谢谢! :D
  • 喜欢static const 而不是枚举破解
  • @Manu343726:静态 constexpr 优于静态 const。 enum 与 const 之间的胜者似乎并不清楚。
  • @Manu343726 你能举一个使用static const的解决方案的例子吗?
  • @cmbasnett template&lt;&gt; struct IndexTypeGL&lt;uint8_t&gt; { static constexpr value = GL_UNSIGNED_BYTE; };
猜你喜欢
  • 1970-01-01
  • 2013-06-16
  • 2011-01-10
  • 1970-01-01
  • 2012-12-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-05
相关资源
最近更新 更多