Does there exist a static_warning?
Question:
It is known that Boost provides a "STATIC WARNING" feature. However, this question aims to specifically explore the possibility of implementing a custom static_warning functionality that operates similarly to static_assert but issues a warning at compile time instead of aborting the compilation.
Answer:
Yes, it is possible to implement a custom static_warning feature using either GCC or MSVC. The implementation leverages the macro DEPRECATE to define a warning-emitting function and employs a series of nested macros to create the desired functionality.
Usage:
The custom static_warning can be used like this:
<code class="cpp">STATIC_WARNING(condition, "Warning message here");</code>
…
For instance, this code will issue a warning:
<code class="cpp">STATIC_WARNING(true, "This warning is intended");</code>
Implementation:
The implementation relies on macros to achieve the gewünschten behavior:
<code class="cpp">#define DEPRECATE(foo, msg) foo __attribute__((deprecated(msg))) #define STATIC_WARNING(cond, msg) ... ... struct true_type {}; struct false_type {}; template<int test> struct converter : public true_type {}; template<> struct converter<0> : public false_type {}; ... STATIC_WARNING(cond, msg) { DEPRECATE(void _(const detail::false_type&), msg) {}; void _(const detail::true_type& ) {}; PP_CAT(static_warning,__LINE__)() {_(::detail::converter<(cond)>>());} }</code>
Example:
Consider the following code:
<code class="cpp">STATIC_WARNING(1 == 1, "This is not a warning"); STATIC_WARNING(1 != 1, "This should generate a warning");</code>
When compiled with the appropriate warning level, the second line will trigger a warning.
The above is the detailed content of Can we implement a custom `static_warning` functionality in C ?. For more information, please follow other related articles on the PHP Chinese website!