为什么std :: function的初始化程序必须是CopyConstructible? [英] Why the initializer of std::function has to be CopyConstructible?

查看:163
本文介绍了为什么std :: function的初始化程序必须是CopyConstructible?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据 http://en.cppreference.com/w/ cpp / utility / functional / function / function ,初始化器的类型,即形式(5)中的 F 应该满足CopyConstructible的要求。我不太明白这一点。为什么 F 不能只是MoveConstructible?

According to http://en.cppreference.com/w/cpp/utility/functional/function/function, the type of the initializer, i.e., F in form (5), should meet the requirements of CopyConstructible. I don't quite get this. Why is it not OK for F to be just MoveConstructible?

推荐答案

std :: function在内部使用类型擦除,因此F必须是CopyConstructible,即使特定的std :: function对象

std::function uses type erasure internally, so F has to be CopyConstructible even if the particular std::function object you are using is never copied.

如何简化类型擦除的工作原理:

A simplification on how type erasure works:

class Function
{
    struct Concept {
        virtual ~Concept() = default;
        virtual Concept* clone() const = 0;
        //...
    }

    template<typename F>
    struct Model final : Concept {

        explicit Model(F f) : data(std::move(f)) {}
        Model* clone() const override { return new Model(*this); }
        //...

        F data;
    };

    std::unique_ptr<Concept> object;

public:
    template<typename F>
    explicit Function(F f) : object(new Model<F>(std::move(f))) {}

    Function(Function const& that) : object(that.object->clone()) {}
    //...

};

您必须能够生成 Model< F> :: clone ),这强制F为CopyConstructible。

You have to be able to generate Model<F>::clone(), which forces F to be CopyConstructible.

这篇关于为什么std :: function的初始化程序必须是CopyConstructible?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆