请帮助我理解这种语法(在C ++中实现静态断言) [英] Please help me understand this syntax (implementing static assert in C++)

查看:169
本文介绍了请帮助我理解这种语法(在C ++中实现静态断言)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此语法用作此问题答案的一部分:

This syntax was used as a part of an answer to this question:

template <bool>
struct static_assert;

template <>
struct static_assert<true> {}; // only true is defined

#define STATIC_ASSERT(x) static_assert<(x)>()

我不明白这个语法。它是如何工作的?

假设我做

STATIC_ASSERT(true);

它会转换为

static_assert<true>();

现在是什么?

推荐答案

STATIC_ASSERT(true);

确实意味着

static_assert<true>();

static_assert< true> 只是一个没有任何成员的空结构。 static_assert< true>()创建该结构的对象,不会将其存储在任何位置。

which evaluates to nothing. static_assert<true> is just an empty structure without any members. static_assert<true>() creates an object of that structure and does not store it anywhere.

另一方面

STATIC_ASSERT(false);

表示

static_assert<false>();

这会导致编译错误。 static_assert 没有专门为 false 。所以使用一般形式。但是一般的形式如下:

which results in compilation error. static_assert has no specialization for false. So a general form is used. But the general form is given as follows:

template <bool>
struct static_assert;

这只是一个结构的声明,而不是它的定义。因此, static_assert< false>()会导致编译错误,因为它试图创建未定义的结构的对象。

which is just a declaration of a structure and not its definition. So static_assert<false>() causes compilation error as it tries to make an object of a structure which is not defined.

这篇关于请帮助我理解这种语法(在C ++中实现静态断言)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆