Best and simplest way is to accept any functor, not just std::function
:
template <typename F,typename... T>
auto func(F f, T... values) -> decltype(f(values...)) {
return f(values...);
}
Вопрос
Hello i'm trying to create a function which will make a call to function provided as a parameter with some provided arguments and return its value, my current approach is as follows
#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;
}
if i replace Res with void and remove the auto&&decltype it works, but somehow i'm not able to get the proper return type.
Решение 2
Best and simplest way is to accept any functor, not just std::function
:
template <typename F,typename... T>
auto func(F f, T... values) -> decltype(f(values...)) {
return f(values...);
}
Другие советы
Tossing in one extra alternative (as the above would be too much to digest sometimes).
With c++17 you can do:
template <typename F, typename... T, typename RES = std::invoke_result<F, T...>>
RES func(F f, T... values) {
return f(values...);
}
and then there's also std::result_of
for before C++17.