调用带有std :: function作为lambda参数的函数 [英] Call a function with std::function as argument with a lambda

查看:123
本文介绍了调用带有std :: function作为lambda参数的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从这里得到的问题的依据是:
无法从lambda函数推断出模板参数std :: function
此线程中的问题是:
为什么此代码无法将lambda传递给函数:

The basis from my question I took from here: Failure to deduce template argument std::function from lambda function The question in this thread is: Why this code can't pass the lambda to the function:

#include <iostream>
#include <functional>

template <typename T>
void call(std::function<void(T)> f, T v)
{
    f(v);
}

int main(int argc, char const *argv[])
{
    auto foo = [](int i) {
        std::cout << i << std::endl;
    };
    call(foo, 1);
    return 0;
}

此线程的答案是,因为lambda不是 std :: function 。但是为什么要编译此代码:

The answer in this thread is, since a lambda isn't a std::function. But why is this code compiling:

#include <iostream>
#include <functional>

template <typename T>
void call(std::function<void(T)> f, T v)
{
    f(v);
}

int main(int argc, char const *argv[])
{
    auto foo = [](int i) {
        std::cout << i << std::endl;
    };
    call({foo}, 1); // changed foo to {foo}
    return 0;
}


推荐答案

如链接答案中所述,第一个版本无法编译,因为第一个参数的模板参数推导失败; Lambda永远不是 std :: function< void(T)>

As written in the linked answer, the first version does not compile, because template argument deduction fails for the first argument; a lambda is never an std::function<void(T)>.

第二个版本会编译,因为通过编写 {foo} std :: function< void(T)> 成为非推论情境。因此,推论不会因为第一个参数而失败,因为甚至没有尝试。因此,仅从第二个参数就将 T 推导出为 int ,并且调用成功,因为lambda可转换为 std :: function< void(int)>

The second version compiles, because, by writing {foo}, std::function<void(T)> becomes a non-deduced context. So deduction can no longer fail for the first argument, as it isn't even attempted. So T is deduced as int solely from the second argument, and the call succeeds, because the lambda is convertible to an std::function<void(int)>.

来自[temp.deduct.type]:

From [temp.deduct.type]:


非推论上下文为:

The non-deduced contexts are:


  • ...

  • 一个函数参数,其关联参数为初始值设定项列表,但参数
    不具有为其指定从初始值设定项列表中推论的类型。 li>
  • ...
  • A function parameter for which the associated argument is an initializer list but the parameter does not have a type for which deduction from an initializer list is specified.

这篇关于调用带有std :: function作为lambda参数的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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