将C ++模板类型限制为特定的变量大小

时间:2013-03-19 15:23:09

标签: c++ templates

我想知道是否可以将模板类型限制为特定大小的变量类型? 假设我想接受4字节变量并拒绝所有其他变量,如果在某些编译器上运行此代码,其中sizeof(int)== 4和sizeof(bool)== 1:

template <class T> FourOnly {...};
FourOnly<int> myInt; // this should compile
FourOnly<bool> myBool; // this should fail at compilation time

有什么想法吗? 谢谢!

2 个答案:

答案 0 :(得分:10)

您可以使用静态断言:

template <class T> FourOnly 
{
  static_assert(sizeof(T)==4, "T is not 4 bytes");
};

如果您没有相关的C ++ 11支持,可以查看boost.StaticAssert

答案 1 :(得分:2)

std::enable_if不是4时,您可以使用sizeof(T)禁止编译。

template<typename T,
         typename _ = typename std::enable_if<sizeof(T)==4>::type
        >
struct Four
{};

但是,我更喜欢other answer中的static_assert解决方案。