这是一个简单示例的摘录(请参阅 full source live here):
class Foo final {
public:
int var;
inline Foo(void) {
static_assert(sizeof(Foo)==sizeof(int),"Implementation error!");
}
static_assert(sizeof(Foo)==sizeof(int),"Implementation error!");
};
在最近的 g++ 上(注意 MSVC 没有提示),这会产生如下内容:
error: invalid application of ‘sizeof’ to incomplete type ‘Foo’
该错误仅发生在第二个static_assert
上。
我知道类的定义还没有词法写完,但是肯定有一个完整类型的所有信息,对吧?我的意思是,我们在里面。即使不是,为什么它会在方法中起作用?
最佳答案
类类型在它自己的成员函数体内是完整的(正如 Matt 所说,函数体的处理是延迟的)。它在类定义的 {}
内的大多数其他地方都不完整,包括那个 static_assert
。 9.2 节的规则是
A class is considered a completely-defined object type (or complete type) at the closing
}
of the class-specifier. Within the class member-specification, the class is regarded as complete within function bodies, default arguments, using-declarations introducing inheriting constructors (12.9), exception-specifications, and brace-or-equal-initializers for non-static data members (including such things in nested classes). Otherwise it is regarded as incomplete within its own class member-specification.
想一想,编译器应该怎么知道你没有
int another_var;
紧接在 static_assert
之后?
static_assert
的最佳位置可能是在类定义之后的命名空间范围内。
关于c++ - 不能在类范围内使用 `static_assert` 和 `sizeof`(但方法范围没问题),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28576449/