此语法用作对 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>()
创建该结构的对象并且不将其存储在任何地方。
这只是编译,什么都不做。
另一方面
STATIC_ASSERT(false);
表示
static_assert<false>();
导致编译错误。 static_assert
没有 false
的特化.所以使用了一个通用的形式。但一般形式给出如下:
template <bool>
struct static_assert;
这只是一个结构的声明,而不是它的定义。所以static_assert<false>()
导致编译错误,因为它试图创建一个未定义结构的对象。
关于c++ - 请帮助我理解这种语法(在 C++ 中实现静态断言),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3099445/