首页 >后端开发 >C++ >是否存在相当于'static_assert”的静态警告,它会产生警告而不是停止编译?

是否存在相当于'static_assert”的静态警告,它会产生警告而不是停止编译?

DDD
DDD原创
2024-10-31 20:01:29317浏览

Is there a static warning equivalent to `static_assert` that produces a warning instead of halting compilation?

有静态警告吗?

这个问题旨在确定是否存在一种机制来实现类似于 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&amp; ),msg) {}; \
  void _(::detail::true_type const&amp; ) {}; \
  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 5

以上是是否存在相当于'static_assert”的静态警告,它会产生警告而不是停止编译?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn