Pass Member Function as Parameter to other Member Function (C++ 11 <function>)
If you truly want to pass the member function, you need a member function pointer
class ClassName
{
public:
double add(double a, double b);
using Combiner = double (ClassName::*)(double, double);
double intermediate(double a, double b, Combiner);
double combiner(double a, double b);
};
This will only slightly change the implementation of intermediate
and combiner
double ClassName::intermediate(double a, double b, Combiner func)
{
return (this->*func)(a, b);
}
double ClassName::combiner(double a, double b)
{
return intermediate(a, b, &ClassName::add);
}
ClassName::add
is a non-static member function, an instance of ClassName
is needed for it to be called on; it can't be used as the argument for std::function<double (double,double)>
directly.
You can use lambda and capture this
(as @Igor Tandetnik commented):
return intermediate(a, b, [this](double x, double y) { return add(x, y); } );
or use std::bind and bind this
pointer:
return intermediate(a, b, std::bind(&ClassName::add, this, _1, _2));
or make ClassName::add
a static member function or a non-member function (it could be because it doesn't use any members of ClassName
). e.g.
class ClassName
{
public:
static double add(double a, double b);
...
};