Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/dart/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 静态断言内部/外部类定义_C++_C++11_Typetraits_Static Assert - Fatal编程技术网

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
)参数的表达式要求类类型完整才能正常工作。但是class
A
class-type
A
的内部定义还不完整,这使得您的参数表达式无效。这就是为什么您的
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
可以在函数体内部使用