c++ - 将 lambda 作为模板参数传递 : what type is actually deduced?

标签 c++ lambda c++14 std-function template-argument-deduction

如果我将 lambda 作为模板参数传递,推导的该参数的实际类型是什么?我查看了 VS2017 调试器和此 lambda 的类型:[](int x) {return x; }filename::__I2::int<lambda>(int) .

我问这个的原因是因为我想传递一个 lambda 然后创建一个内部 std::function由此。请注意,这与 this answer 有关以及为什么我们必须使用 CTAD 构建内部 std::function而不是仅仅将模板参数传递给 std::function .

例如,我想执行以下操作:

template<class Func, class... Args> 
void createStdFunc(Func f, Args... args) {
    std::function<Func> internalFunc = f; //this does not work
}

//usage
createStdFunc([](int x) {return x; }, 5);

但是,这不起作用,我收到错误 'initialising' cannot convert from 'Func' to 'std::function<Func>' .我不确定类型有何不同以及它们从传递到函数到初始化 std::function 是如何变化的.请注意,我知道您可以从 2017 年开始使用 CTAD,但想知道 2014 年及之前的解决方案是什么?

最佳答案

在 C++14 中,您可以使用返回类型推导来计算函数签名,这意味着传递给 createStdFunc 的参数类型匹配:

template<class Func, class... Args> 
void createStdFunc(Func f, Args... args) {
    std::function<std::result_of_t<Func(Args...)> (Args...)> internalFunc{f}; //this does work
}

关于c++ - 将 lambda 作为模板参数传递 : what type is actually deduced?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55521783/

相关文章:

c++ - 使用 -g 和不使用 -DNDEBUG 选项的链接时间非常长

lambda - 引用 Kotlin 中特定实例的方法

c# - 在 C# 中,=> 符号的含义

c++ - 派生类型的大括号初始化

c++ - 获取右值引用的地址是什么意思?

c++ - 在临时字符串上使用基于范围的循环时为空字符?

c++ - 从循环中提升动态类型(也就是以 C++ 方式执行 Java)

c++ - 测试 C++ 容器 - insert 和 push_back 的结果

c# - 我需要杀死这样写的线程吗?还是会自动结束?

c++ - std::vector<T> 是 `user-defined type` 吗?