Limit the type of C ++ template to a specific variable size

I was wondering if it is possible to restrict the type of a template to a variable type of a certain size? Assuming I want to accept a 4-byte variable and reject all the others if this code is executed in the 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? Thank!

+5
source share
2 answers

You can use a static statement:

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

If you don't have the appropriate support in C ++ 11, you can look at boost.StaticAssert .

+10
source

You can use std::enable_ifto disable compilation, if sizeof(T)not 4.

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

static_assert .

+2

All Articles