I have a class C
with a method func
. C
also has a data member m_func_taker
whose constructor takes a std::function
argument. How can I pass in C::func
into m_func_taker
's constructor?
I have some example code (click here to run):
#include <iostream>
#include <functional>
template<typename out_t, typename in_t>
struct my_type{
using F = std::function<out_t(in_t)>;
F m_f;
my_type(F f) : m_f(f) {}
};
class C{
public:
my_type<double,double> m_func_taker;
double func(double in) {
return 2*in;
}
C() : m_func_taker(func) {}
};
int main() {
// your code goes here
return 0;
}
I get the following error: "prog.cpp:19:25: error: invalid use of non-static member function ‘double C::func(double)’ C() : m_func_taker(func) {}"
It compiles fine when I change the method to static
and change
C() : m_func_taker(C::func) {}
but I can't do that in my real program.
You could wrap the call to the method in a lambda:
C() : m_func_taker([this](auto d) { return this->func(d); }) {}
Here's a demo.
To construct a std::function
from a method of a class, you could use std::bind
:
using std::placeholders::_1;
C() : m_func_taker(std::bind(&C::func, this, _1)) {}
Here's a demo.
From c++20, you could simplify this with std::bind_front
:
C() : m_func_taker(std::bind_front(&C::func, this)) {}
Here's a demo.