Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Restrict a C++ template type to a specific variable size

Tags:

c++

templates

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!

like image 777
Marco83 Avatar asked Mar 19 '13 15:03

Marco83


2 Answers

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.

like image 138
juanchopanza Avatar answered Oct 12 '22 20:10

juanchopanza


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.

like image 20
Praetorian Avatar answered Oct 12 '22 21:10

Praetorian