我想知道是否可以将模板类型限制为特定大小的变量类型? 假设我想接受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
有什么想法吗? 谢谢!
答案 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
解决方案。