为什么 static_assert 需要在类定义之外?
失败代码
#include <type_traits>
class A
{
public:
A(A&&) noexcept {}
static_assert(std::is_nothrow_move_constructible<A>::value, "ERROR");
};
int main()
{
}
工作代码
#include <type_traits>
class A
{
public:
A(A&&) noexcept {}
};
static_assert(std::is_nothrow_move_constructible<A>::value, "ERROR");
int main()
{
}
什么时候适合在类或结构的定义中使用 static_asserts?
最佳答案
至于 static_assert
的位置本身担心您的代码的两个版本都有效。所以,不,static_assert
不需要在类定义之外。正式static_assert
是一个声明。在任何允许声明的地方都允许。
您遇到的问题与 static_assert
无关自己。
这里的问题是您用作static_assert
参数的表达式( std::is_nothrow_move_constructible
) 要求类类型完整 才能正常工作。但是在类A
的定义里面类(class)类型A
尚未完成,这会使您的参数表达式无效。这就是为什么您的 static_assert
仅在类定义之外按预期工作,其中 A
已经完成。然而,这完全是关于正确使用 std::is_nothrow_move_constructible
,而不是 static_assert
自己。
请注意,即使成员函数是在类定义中定义的,内部成员函数体的类类型也被视为完整类型。使用此功能,您可以将代码重写为
class A
{
public:
A(A&&) noexcept {
static_assert(std::is_nothrow_move_constructible<A>::value, "ERROR");
}
};
和std::is_nothrow_move_constructible<A>
将产生正确的结果。
关于c++ - static_assert 内部/外部类定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25904145/