如果我将 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/