I have a question continuing the post Function passed as template argument. In the provided code:
#include <iostream>
void add1(int &v)
{
v+=1;
}
void add2(int &v)
{
v+=2;
}
template <void (*T)(int &)>
void doOperation()
{
int temp=0;
T(temp);
std::cout << "Result is " << temp << std::endl;
}
int main()
{
doOperation<add1>();
doOperation<add2>();
}
what about a third function which has a different parameter set layout, e.g.
double add3(double v1, double v2)
{
return v1+v2;
}
If this is not achievable using template at all, how do we pass an arbitrary function to another function? And how do we handle the parameter set with all kinds of possibilities? I know python may be able to do it by passing a tuple (kwargs**), but not sure about C/C++.
One form of passing a generic function to be called is a callable templated type:
callFootakes a callable type,F, and calls it. Around this call, you can, for example, do timer work to time the function. Inmain, it’s called with a lambda that has two parameters and the values given to those parameters bound to it.callFoocan then call it without storing the arguments. This is very similar to taking a parameter with the typestd::function<void()>.If, however, you don’t want to use
std::bind, you can pass in the arguments separately with a couple changes:In these cases, passing void functions makes sense. Indeed, return values can be used as parameters and passed in with
std::ref. If you plan on returning what the function returns, you’ll have to handle the special case of the return type beingvoid, as you can’t assign to avoidvariable and return that. At this point, it’s easier to direct you to my previous question on the matter. My use case for it turned out to be moot, but the solution works great for other uses.