我想知道是否可以将模板类型限制为特定大小的变量类型?假设我想接受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
Run Code Online (Sandbox Code Playgroud)
任何的想法?谢谢!
jua*_*nza 10
您可以使用静态断言:
template <class T> FourOnly
{
static_assert(sizeof(T)==4, "T is not 4 bytes");
};
Run Code Online (Sandbox Code Playgroud)
如果您没有相关的C++ 11支持,可以查看boost.StaticAssert.