问题
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?
回答1:
You might consider using Boost's static assert.
Note on the boost website:
Boost libraries are intended to be widely useful, and usable across a broad spectrum of applications.
For this reason, boost usually intentionally lags behind in use of language features. You can find the compiler compatibility list here.
If you must roll your own implementation, then here is a Dr. Dobbs article. If I'm not mistaken, Andrei Alexandrescu wrote about this in his Modern C++ Design.
回答2:
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).
来源:https://stackoverflow.com/questions/30266009/availability-of-static-assert-c11