std::函数如何工作

How std::function works

本文关键字:工作 何工作 函数 std      更新时间:2023-10-16

你知道,我们可以将lambda函数包装或存储到std::function

#include <iostream>
#include <functional>
int main()
{
    std::function<float (float, float)> add = [](float a, float b)
    //            ^^^^^^^^^^^^^^^^^^^^
    {
        return a + b;
    };
    std::cout << add(1, 2) << std::endl;
}

我的问题大约是std::function,如您所见,它是一个模板类,但它可以接受任何类型的函数签名

例如,float (float, float)以这种形式return_value (first_arg, second_arg) .

std::function的结构是什么,它如何接受像x(y,z)这样的函数签名以及它如何与之配合?float (float, float)是C++中的新有效表达式吗?

它使用某种类型擦除技术。

一种可能性是将混合子类型多态性与模板一起使用。这是一个简化版本,只是为了给整体结构一个感觉:

template <typename T>
struct function;
template <typename Result, typename... Args>
struct function<Result(Args...)> {
private:
    // this is the bit that will erase the actual type
    struct concept {
        virtual Result operator()(Args...) const = 0;
    };
    // this template provides us derived classes from `concept`
    // that can store and invoke op() for any type
    template <typename T>
    struct model : concept {
        template <typename U>
        model(U&& u) : t(std::forward<U>(u)) {}
        Result operator()(Args... a) const override {
            t(std::forward<Args>(a)...);
        }
        T t;
    };
    // this is the actual storage
    // note how the `model<?>` type is not used here    
    std::unique_ptr<concept> fn;
public:
    // construct a `model<T>`, but store it as a pointer to `concept`
    // this is where the erasure "happens"
    template <typename T,
        typename=typename std::enable_if<
            std::is_convertible<
                decltype( t(std::declval<Args>()...) ),
                Result
            >::value
        >::type>
    function(T&& t)
    : fn(new model<typename std::decay<T>::type>(std::forward<T>(t))) {}
    // do the virtual call    
    Result operator()(Args... args) const {
        return (*fn)(std::forward<Args>(args)...);
    }
};

(请注意,为了简单起见,我忽略了几件事:它无法复制,也许还有其他问题;不要在实际代码中使用此代码(