首页 > 解决方案 > 如何将类的非静态方法传递给类的数据成员的构造函数

问题描述

我有一个C方法类funcC还有一个数据成员m_func_taker,其构造函数接受一个std::function参数。我怎样才能C::func传入m_func_taker's 的构造函数?

我有一些示例代码(单击此处运行):

#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) {}

但我不能在我的真实程序中做到这一点。

标签: c++std-function

解决方案


您可以将对该方法的调用包装在 lambda 中:

C() : m_func_taker([this](auto d) { return this->func(d); }) {}

这是一个演示


要从类的方法构造 a 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)) {}

这是一个演示


推荐阅读