Function calling any given function

How to write a function that calls any specified function (or function object) with the specified arguments?

Here is what I tried:

#include <iostream> #include <functional> using namespace std; template <typename RetType, typename... ArgTypes> RetType q(function<RetType(ArgTypes...)> f, ArgTypes... args) { return f(args...); } int h(int a, int b, int c) { return a + b + c; } int main() { auto r = q(h, 1, 2, 3); cout << "called, result = " << r; return 0; } 

The compiler says that the template argument deduction / substitution failed because of the inconsistent types 'std :: function <_Res (_ArgTypes ...)>' and 'int (*) (int, int, int)'.

I am not sure why template arguments cannot be output in my code.

+5
source share
2 answers

Since this is a template, you do not need std::function . Just do the following:

 template <class F, class... Arg> auto q(F f, Arg... arg) -> decltype(f(arg...)) { return f(arg...); } 

Better yet, use perfect forwarding:

 template <class F, class... Arg> auto q(F f, Arg&&... arg) -> decltype(f(std::forward<Arg>(arg)...)) { return f(std::forward<Arg>(arg)...); } 
+3
source

You are probably setting the hard way for a simple problem ... You can just use a closure that doesn't require parameters for this ...

 #include <iostream> #include <functional> using namespace std; int h(int a, int b, int c) { return a + b + c; } int main() { auto clsr = [](){ return h(1, 2, 3); }; auto r = clsr(); cout << "called, result = " << r; return 0; } 

with the advantage that the IDE will even offer arguments for h when writing / editing such code.

0
source

All Articles