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!
You could use a static assertion:
template <class T> FourOnly
{
static_assert(sizeof(T)==4, "T is not 4 bytes");
};
If you don't have the relevant C++11 support, you could have a look at boost.StaticAssert.
You can use std::enable_if
to disallow compilation when sizeof(T)
is not 4.
template<typename T,
typename _ = typename std::enable_if<sizeof(T)==4>::type
>
struct Four
{};
However, I'd prefer the static_assert
solution in the other answer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With