+ 2

Make a function which executes others in C++?

I need a function which as the first parameter it takes a pointer to a function, and the other ones are just parameters for the function(the function can have any number of parameters). For example, if I define a function int add(int a, int b) I could execute it with the wanted function with: wantedF(address of function "add", x, y) and would return an int. Is this possible for arbitrary function? Thanks.

7th Sep 2017, 2:39 AM
Testing003
4 Respuestas
+ 2
C++03 and C++11 have undergone a lot of changes, and now, we have variadic templates. Thus, the wantedF() function to execute a function can now be declared for arbitrary functions : template<typename Fx, Fx fn, typename... Args> typename std::result_of<Fn(Args...)>::type wantedF (Args&&... args) { return fn(std::forward<Args>(args)...); } This is called as : wantedF<decltype(&add),&add>(2,3); Now, to shorten it for use, you may use a define: #define exec(fx) wantedF<decltype(&fx),&fx> Then use it like this : int add(int a,int b){ return a+b;} int sub(int a,int b,int c){ return a-b-c;} int main() { int sum = exec (add)(2,3); int diff = exec(sub)(2,3,4); cout << sum << " " << diff ; // Prints 5 and -5... } NOTE - You may require <type_traits> for the function result_of.
7th Sep 2017, 4:17 AM
Solo Wanderer 4315
Solo Wanderer 4315 - avatar
+ 2
There are two ways of doing it: #include <iostream> #include <functional> int add(int a, int b) { return a + b; } int wantedF(const std::function<int(int, int)>& function, int x, int y) { return function(x, y); } template<typename t> int wantedF2(t* function, int x, int y) { return function(x, y); } int main() { std::cout << wantedF(&add, 2, 2) << "\n"; std::cout << wantedF2(&add, 2, 2) << "\n"; std::cin.get(); } wantedF is the safest and recommended way to do it.
7th Sep 2017, 4:28 AM
aklex
aklex - avatar
+ 2
@alkex Will any of those ways work for the following function? int add3 (int a, int b, int c) {return a+b+c;}
7th Sep 2017, 4:31 AM
Solo Wanderer 4315
Solo Wanderer 4315 - avatar
+ 2
Of course, and if he wants it to be arbitrary, you can use std::function with template args
7th Sep 2017, 4:42 AM
aklex
aklex - avatar