我有一个类C
,方法为func
。C
还有一个数据成员m_func_taker
,其构造函数采用std::function
参数。如何将C::func
传递到m_func_taker
的构造函数中?
我有一些示例代码(单击此处运行(:
#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;
}
我得到以下错误:;prog.cpp:19:25:错误:无效使用非静态成员函数"double C::func(double("C((:m_func_taker(func({}">
当我将方法更改为static
并更改时,它编译得很好
C() : m_func_taker(C::func) {}
但我不能在我的真实程序中做到这一点。
您可以将对方法的调用包装在lambda:中
C() : m_func_taker([this](auto d) { return this->func(d); }) {}
这是一个演示。
要从类的方法构造std::function
,可以使用std::bind
:
using std::placeholders::_1;
C() : m_func_taker(std::bind(&C::func, this, _1)) {}
这是一个演示。
从c++20,您可以使用std::bind_front
:简化此过程
C() : m_func_taker(std::bind_front(&C::func, this)) {}
这是一个演示。
您可以使用lambda(绑定this
指针(:
class C {
...
C() : m_func_taker ([this] (double in) { return this->func (in); }) {}
};