简体   繁体   中英

how to pass in class' non-static method into class' data member's constructor

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 .

You can do it with a lambda (to bind the this pointer):

class C {
...    
    C() : m_func_taker ([this] (double in) { return this->func (in); }) {}
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM