您好,我正在尝试创建一个函数,它将调用作为参数提供的函数以及一些提供的参数并返回其值,我当前的方法如下
#include <functional>
#include <iostream>
#include <type_traits>
template <typename Res,typename... T>
auto func(typename std::common_type<std::function<Res(T...)>>::type f, T... values) -> decltype(f(values...)) {
f(values...);
}
int fx(int x,int y){return x+y; }
int main() {
>> func([](int x, int y, int z) { std::cout << (x*y*z) << std::endl; }, 3, 6, 8);
return 0;
}
如果我用 void 替换 Res 并删除 auto&&decltype 它可以工作,但不知何故我无法获得正确的返回类型。
最佳答案
加入一种额外的替代方案(因为上面的内容有时会难以消化)。
使用 c++17 你可以这样做:
template <typename F, typename... T, typename RES = std::invoke_result<F, T...>>
RES func(F f, T... values) {
return f(values...);
}
还有 C++17 之前的 std::result_of
。
关于templates - 推断模板中的 lambda 返回类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20121262/