這個問題旨在確定是否存在一種機制來實現類似於 static_assert 的靜態警告,但它不會停止編譯,而是觸發編譯期間的警告訊息。
利用Michael E 的評論提供的見解,建議以下實現:
<code class="c++">#if defined(__GNUC__) #define DEPRECATE(foo, msg) foo __attribute__((deprecated(msg))) #elif defined(_MSC_VER) #define DEPRECATE(foo, msg) __declspec(deprecated(msg)) foo #else #error This compiler is not supported #endif #define PP_CAT(x,y) PP_CAT1(x,y) #define PP_CAT1(x,y) x##y namespace detail { struct true_type {}; struct false_type {}; template <int test> struct converter : public true_type {}; template <> struct converter<0> : public false_type {}; } #define STATIC_WARNING(cond, msg) \ struct PP_CAT(static_warning,__LINE__) { \ DEPRECATE(void _(::detail::false_type const& ),msg) {}; \ void _(::detail::true_type const& ) {}; \ PP_CAT(static_warning,__LINE__)() {_(::detail::converter<(cond)>());} \ } // Note: using STATIC_WARNING_TEMPLATE changes the meaning of a program in a small way. // It introduces a member/variable declaration. This means at least one byte of space // in each structure/class instantiation. STATIC_WARNING should be preferred in any // non-template situation. // 'token' must be a program-wide unique identifier. #define STATIC_WARNING_TEMPLATE(token, cond, msg) \ STATIC_WARNING(cond, msg) PP_CAT(PP_CAT(_localvar_, token),__LINE__)</code>
宏可以在多個範圍內調用,包括命名空間、結構和函數。以下是範例:
<code class="c++">#line 1 STATIC_WARNING(1==2, "Failed with 1 and 2"); STATIC_WARNING(1<2, "Succeeded with 1 and 2"); struct Foo { STATIC_WARNING(2==3, "2 and 3: oops"); STATIC_WARNING(2<3, "2 and 3 worked"); }; void func() { STATIC_WARNING(3==4, "Not so good on 3 and 4"); STATIC_WARNING(3<4, "3 and 4, check"); } template <typename T> struct wrap { typedef T type; STATIC_WARNING(4==5, "Bad with 4 and 5"); STATIC_WARNING(4<5, "Good on 4 and 5"); STATIC_WARNING_TEMPLATE(WRAP_WARNING1, 4==5, "A template warning"); }; template struct wrap<int>;</code>
啟用適當的編譯器警告後,提供的實作會在編譯時產生警告訊息,傳達指定的訊息:
GCC 4.6:
static_warning1::_: Failed with 1 and 2 Foo::static_warning6::_: 2 and 3: oops func()::static_warning12::_: Not so good on 3 and 4 wrap<T>::static_warning19::_: Bad with 4 and 5
Visual C 2010:
'static_warning1::_': Failed with 1 and 2 'Foo::static_warning6::_': 2 and 3: oops 'func::static_warning12::_': Not so good on 3 and 4 'wrap<T>::static_warning19::_': Bad with 4 and 5
Clang 3.1:
'_' is deprecated: Failed with 1 and 2 '_' is deprecated: 2 and 3: oops '_' is deprecated: Not so good on 3 and 4 '_' is deprecated: Bad with 4 and 5Clang 3.1:
以上是是否存在相當於'static_assert”的靜態警告,它會產生警告而不是停止編譯?的詳細內容。更多資訊請關注PHP中文網其他相關文章!