我正在尝试与std::function相处。从引用here可以看到std::function的ctor的参数应该是可调用的并且可以复制构造。所以这是一个小例子:

#include <iostream>
#include <type_traits>
#include <functional>

class A {
public:
    A(int a = 0): a_(a) {}
    A(const A& rhs): a_(rhs.a_) {}
    A(A&& rhs) = delete;
    void operator() ()
    {
        std::cout << a_ << std::endl;
    }

private:
    int a_;
};

typedef std::function<void()> Function;

int main(int argc, char *argv[])
{
    std::cout << std::boolalpha;
    std::cout << "Copy constructible: "
              << std::is_copy_constructible<A>::value << std::endl;
    std::cout << "Move constructible: "
              << std::is_move_constructible<A>::value << std::endl;
    //Function f = A();
    return 0;
}

我们有可调用,可复制构造但不能移动的构造类。我相信这足以将其包装在Function中。但是,如果您取消注释,行编译器将对删除的move构造函数感到非常沮丧。这是ideone链接。 GCC 4.8.0也不编译它。

那么,是我对std::function误解了还是GCC的错误行为?

最佳答案

GCC和Clang是正确的。

注意:

即如果某些东西是CopyConstructible,那么它也必须是MoveConstructible。虽然可以将移动实现为副本很好。
更新:
尽管我发现有趣的是C++ 11标准似乎没有按照CopyConstructible来定义is_copy_constructible,即它们并不完全相同,但是is_copy_constructible更为宽松,因为它只需要:

09-05 13:37
查看更多