Search code examples
c++c++11static-assert

Availability of static_assert c++11


I would like to start using static_assert in the codebase that I work on. Unfortunately, not all C++ compilers support them. In the past, we've used a compile-time assert macro that works reasonably for all the compilers I've tried (gleaned from SO!), but, it gives slightly awkward compile error messages.

We support a large number of compilers, including ones which do not have support for static_assert. Also, because our product is an SDK with source code our customers can recompile it with any compiler that they wish. So, while I could introduce conditional compilation for it in all the compilers we use, it's not really possible for me to do it for any 'unknown' compiler.

Is there some compile-time predefined macro or other facility that is standard across all C++ compilers for determining the availability of static_assert, or, are you just required to 'know' what every compiler supports?


Solution

  • In C++14, there are feature test macros, which allow you to generalize the use of C++11/14/17 features. For static_assert, the macro is __cpp_static_assert.

    If your compiler does not inherently support these (yet), you can define them, based on knowledge of what your compiler does support, but they will be forward compatible with any standardized 'unknown' compiler.

    Note: this answer was obtained from a question I asked generalizing this one, to any C++11 feature (Availability of C++11 features). I think there was some confusion about the motivation of this particular case, and the answers given tried to solve providing a nice static assert, more than than the actual question as it was asked (which, they didn't actually do).