c++ - static_assert 内部/外部类定义

标签 c++ c++11 typetraits static-assert

为什么 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/

相关文章:

c++ - 是否允许获取未定义函数的地址?

c# - 从 WindowsCE 上的非托管 C++ 应用程序调用 C# Dll

c++ - 如何使用迭代而不是递归将值输入到链表中?

c++ - 在 C++ 11 线程中通过引用传递;变化是本地化的

c++ - 将指针设置为 nullptr 会影响指向同一地址的其他指针吗?

c++ - 在 C++0x 标准中使用/定义了什么样的 "Traits"

在 T1 和 T2 之间选择的 C++ 类型特征

c++ - 移植到 64 位时如何避免 size_t 到 int 转换警告?

c++ - 为什么我不能使用 fstream vector ?

c++ - 检测结构是否有填充