【问题标题】:std::is_copy/move_constructible fails even though copy/move constructors are defaulted即使默认复制/移动构造函数,std::is_copy/move_constructible 也会失败
【发布时间】:2015-06-25 15:56:57
【问题描述】:

我有一个 Input 类,它有默认的移动/复制构造函数。

Input(const Input &) = default;
Input(Input &&) = default;

但是,以下断言失败。

static_assert(std::is_copy_constructible<Input>(), "Input is not copy-constructible");
static_assert(std::is_move_constructible<Input>(), "Input is not move-constructible");

这是为什么呢?

这是一个完整的例子:

#include <type_traits>

class A {
public:
    A(const A &) = default;
    static_assert(std::is_copy_constructible<A>(), "");
};

int main() {
    // your code goes here
    return 0;
}

【问题讨论】:

  • 您没有向我们提供足够的信息来回答您的问题。
  • 你使用的是哪个编译器?
  • 请通过editSSCCE 提出您的问题。
  • 我添加了一个活生生的例子。

标签: c++ copy-constructor c++14 move-constructor


【解决方案1】:

您的问题是 static_assert 在类声明中。编译器无法确定何时到达static_assert,该类是可复制构造还是可移动构造,因为该类尚未完全定义。

【讨论】:

    【解决方案2】:

    问题是你在类本身中有测试。为了评估static_assert,编译器需要完成该类。这是不可能的,因为需要为此评估 static_assert。这是一个先有鸡还是先有蛋的问题。

    【讨论】:

      【解决方案3】:

      这段代码 sn-p (live on Ideone) 似乎工作得很好:

      #include <type_traits>
      
      class Input {
      public:
        Input(const Input &) = default;
        Input(Input &&) = default;
      };
      
      int main() {
        static_assert(std::is_copy_constructible<Input>(), "");
        static_assert(std::is_move_constructible<Input>(), "");
      }
      

      【讨论】:

      • @gartenriese:在你的 sn-p 中,如果你将你的 static_assert 从你的类定义中移到 main 中,它似乎工作正常。
      【解决方案4】:

      在您的示例中,您将构造函数隐式声明为私有(类类型中的默认可访问性)。

      如果您的真实代码中也是这种情况,那可能就是问题所在。

      【讨论】:

      • 抱歉,这是一个错字,我编辑了我的实时示例。它们是公开的。
      猜你喜欢
      • 2013-03-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多