How to do static_assert with macros?

Prior to C++11 I would normally do:

typedef int static_assert_something[something ? 1 : -1];

You can also look at boost static assert. But it is too bloated for my liking. It is easy to make things bigger, it is hard to make them any better.


Consider something like Boost.StaticAssert, although if that is unavailable to you you can try defining a template.

template<bool>
struct static_assertion;

template<>
struct static_assertion<true> {};

Though that has the drawback of not having a message associated to it.

After a bit of searching through StackOverflow, I stumbled upon this question which had a similar answer to mine and a bunch of alternatives for doing it without boost.


This is basically Maxim's answer with a little more convenient interface. I have taken it from here. Nice thing about it is that the use of templates prevents the user from passing a non-compile-time-constant value as the condition.

template<bool Is_Condition_Met>
struct Static_assert_cpp98
{
  static void apply() {static const char junk[ Is_Condition_Met ? 1 : -1 ];}
};

template<>
struct Static_assert_cpp98<true>
{
  static void apply() {}
};

#define STATIC_ASSERT_CPP98(condition) Static_assert_cpp98<condition>::apply()