Static claims template type size when instantiated

I want to check the size of the next structure when creating with static_assert to limit that the unnamed struct tightly packed, so size A equivalent to sizeof(T) * 3 .

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

This can be done using

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

but

  • since A<T> is still an incomplete type inside its class definition, so the above static_assert in the class definition is not an option

  • static_assert with sizeof does not evaluate inside non-instantiated functions in all compilers (e.g. Clang), so including it in a dummy member function is not an option

  • placing static_assert constructor or destructor will be a solution, but in the above example there is no user-defined constructor (think about aggregates), moreover, imagine a case with several constructors where I would avoid executing the statement in all of them

  • inherits A from another structure, and the execution of static_assert is that in the definition of A will be a solution, but I want the structure to be simple without messing around with auxiliary structures

Any other solution that I am missing?

I decided to restore this issue and leave it open for possible solutions in the future.

+5
source share
1 answer

One special member function (almost) guaranteed by instantiation is a destructor:

 ~A() noexcept { static_assert(sizeof(A<T>) == sizeof(T) * 3, "hey something went wrong"); } 
0
source

Source: https://habr.com/ru/post/1246004/


All Articles