mardi 29 mars 2016

Static assert the size of a template type on instantiation

I want to check the size of the following structure on instantiation with static_assert to constrain that the unnamed struct is tightly packed, thus the size of A is equivalent to sizeof(T) * 3.

template <typename T>
struct A
{
   union
   {
      struct { T a, b, c; };
      T arr[3];
   };
};

This could be done with

static_assert(sizeof(A<T>) == sizeof(T) * 3, "hey something went wrong");

However

  • the sizeof operator on incomplete types is not allowed, so putting it into the class definition is not an option
  • static_assert with sizeof doesn't evaluate inside un-instantiated functions in all compilers (like Clang), so putting it into a dummy member function is not an option
  • putting static_assert to a constructor would be a solution, but in the above example no user-defined constructor exists, furthermore imagine the case of multiple constructors, where I would avoid performing the assertion in all of them
  • inheriting A from an another struct, and performing static_assert on that in the definition of A would be a solution, but I want to keep the struct simple, without messing with helper structures

Any other solution I'm missing?

Aucun commentaire:

Enregistrer un commentaire