How to do static_assert with macros?

醉酒当歌 提交于 2019-11-27 15:57:14

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.

Rapptz

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()

If you add call to the method in question (a.foo();), the static assert will fail (just then the method will be compiled). You do know that you should not static assert on run time values like "k" I presume.

int foo(const int k)
{
  STATIC_ASSERT( k > 9, error_msg );
  return k+5;
}

Static assertions only work with compile-time constant expressions.

k is not a compile-time constant expression.

Non-type template parameters are compile-time constant expressions during template instantiation, so you could adapt your code thus:

template <int K>
int foo()
{
  STATIC_ASSERT( K > 9, error_msg );
  return K+5;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!