【问题标题】:How std::function worksstd::function 的工作原理
【发布时间】:2013-02-18 12:39:13
【问题描述】:

您知道,我们可以将 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++ 中新的有效表达式吗?

【问题讨论】:

  • 在 C++ 中查找类型擦除。
  • 您可以随时打开编译器的 &lt;function&gt; 标头(我相信所有主要编译器都将标准标头作为 C++ 代码提供)并检查它,或者查看 Boost.Function
  • @Angew:是的,很有教育意义,+1。我认为std::function 几乎涉及 C++ 语言的各个方面...
  • 为了更轻松地进行心理锻炼,请尝试了解 std::bind 的工作原理...
  • 您可以在stackoverflow.com/a/14741161/1762344查看实施情况

标签: c++ c++11


【解决方案1】:

它使用了一些type erasure technique

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

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)...);
    }
};

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

【讨论】:

  • +1。非常遗憾我不能为这个答案投票更多次。
  • @Martinho,“不合格”的定义在哪里?
  • @xmllmx 这是一个别名模板,用于从类型中删除所有限定符(const、volatile、& 和 &&)。与Bare 相同:flamingdangerzone.com/cxx11/2012/05/29/…(后来我改变了主意,发现 Unqualified 是一个更好的名字:)
  • @xmllmx,实际上,从头开始。它应该是 std::decay (它模拟按值传递的语义,这就是我想要的:我想按值存储)。它们很相似,但在这里并不完全相同。
  • @Martinho,function::operator () 中缺少参数名称“args”。请添加它以使代码完整。
猜你喜欢
  • 2021-08-15
  • 1970-01-01
  • 2013-04-16
  • 2018-05-26
  • 1970-01-01
  • 1970-01-01
  • 2021-06-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多