For function parameters of template functions I find myself often wrapping member functions inside a lambda to create identical standalone functions with the first parameter being the object.
A (dummy) example :
class A
{
public:
double f1() const;
double f2(int i) const;
// some data
};
template <typename Func>
double calculateSum(std::vector<A> as, Func f)
{
double result = 0.0;
for (auto a : as)
result += f(a);
return result;
}
int main()
{
std::vector<A> as;
int i = 0;
auto sum1 = calculateSum(as, [](const A& a) { return a.f1(); });
auto sum2 = calculateSum(as, [&i](const A& a) { return a.f2(i); });
return 0;
}
Is there a way to define such lambdas more generically ? or is there a way to directly refer to the member functions instead of using lambdas ?
After some researching, thanks to the suggestion of @happydave, I'll go with the following answer:
auto sum1 = calculateSum(as, std::mem_fn(&A::f1));
The second sum cannot be dealt with as such and should remain a lambda. However, in general, it appears to be the less likely case that the client code is the supplier of the arguments (in which case the arguments need to be passed anyhow to the template function (and a lambda capture is a great way)). In many cases, the template function supplies also the passed function's arguments and std::mem_fn would be fine.