C++ 静态断言内部/外部类定义
为什么静态断言需要在类定义之外 失败代码C++ 静态断言内部/外部类定义,c++,c++11,typetraits,static-assert,C++,C++11,Typetraits,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:
#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()
{
}
#包括
甲级
{
公众:
A(A&&)noexcept{}
静态断言(std::is_nothrow\u move\u constructible::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()
{
}
#include <type_traits>
class A
{
public:
A(A&&) noexcept {}
};
static_assert(std::is_nothrow_move_constructible<A>::value, "ERROR");
int main()
{
}
#包括
甲级
{
公众:
A(A&&)noexcept{}
};
静态断言(std::is_nothrow\u move\u constructible::value,“ERROR”);
int main()
{
}
什么时候在类或结构的定义中使用静态断言是合适的?就
静态断言本身的位置而言,两个版本的代码都是有效的。因此,不,static\u assert
不需要在类定义之外。形式上,static\u assert
是一种声明。只要允许声明,就可以使用它
您遇到的问题与static\u assert
本身无关
这里的问题是,用作static\u assert
(std::is\nothrow\u move\u constructible
)参数的表达式要求类类型完整才能正常工作。但是classA
class-typeA
的内部定义还不完整,这使得您的参数表达式无效。这就是为什么您的static_assert
只能在类定义之外按预期工作,其中A
是完整的。然而,这完全是关于正确使用std::is\u nothrow\u move\u constructible
,而不是static\u assert
本身
请注意,即使成员函数是在类定义中定义的,内部成员函数体类类型也被视为完整类型。使用此功能,您可以将代码重写为
class A
{
public:
A(A&&) noexcept {
static_assert(std::is_nothrow_move_constructible<A>::value, "ERROR");
}
};
A类
{
公众:
A(A&&)无例外{
静态断言(std::is_nothrow\u move\u constructible::value,“ERROR”);
}
};
而且std::nothrow\u move\u constructible
会产生正确的结果。第一个有什么不起作用?是否有错误消息?我已编辑了问题标题以匹配问题内容。@0x499602D2失败的代码在使用g++--std=c++11{code}Is_nothrow_move_constructible.cpp:8:1:错误:静态断言失败:错误静态断言(std::Is_nothrow_move_constructible::value,“error”);{code}和,AFAIK,static_assert
可以在函数体内部使用