5

I was wondering if it is possible to restrict a template type to be a variable type of a specific size? Assuming I want to accept 4-bytes variable and rejects all the others, if running this code on some compiler where sizeof(int) == 4 and sizeof(bool) == 1:

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

Any idea? Thanks!

4

2 回答 2

10

您可以使用静态断言:

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

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

于 2013-03-19T15:25:31.640 回答
3

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

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

但是,我更喜欢其他答案static_assert中的解决方案。

于 2013-03-19T15:28:29.430 回答