Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Please help me understand this syntax (implementing static assert in C++)

This syntax was used as a part of an answer to this question:

template <bool>
struct static_assert;

template <>
struct static_assert<true> {}; // only true is defined

#define STATIC_ASSERT(x) static_assert<(x)>()

I do not understand that syntax. How does it work?

Suppose I do

STATIC_ASSERT(true);

it gets converted to

static_assert<true>();

Now what?

like image 537
Lazer Avatar asked Jun 23 '10 06:06

Lazer


1 Answers

STATIC_ASSERT(true);

indeed means

static_assert<true>();

which evaluates to nothing. static_assert<true> is just an empty structure without any members. static_assert<true>() creates an object of that structure and does not store it anywhere.

This simply compiles and does nothing.

On the other hand

STATIC_ASSERT(false);

means

static_assert<false>();

which results in compilation error. static_assert has no specialization for false. So a general form is used. But the general form is given as follows:

template <bool>
struct static_assert;

which is just a declaration of a structure and not its definition. So static_assert<false>() causes compilation error as it tries to make an object of a structure which is not defined.

like image 65
Adam Badura Avatar answered Oct 07 '22 03:10

Adam Badura