简体   繁体   中英

std function reference to member function through std bind

Let's imagine I define a naive function reference wrapper like follows:

struct wrapper {
    std::function<void(void)>& fct;
    
    wrapper(std::function<void(void)>& _fct) : fct{_fct}{
        fct();    
    };
};

Of course, in reality it is more complex than this, but I simplified it to illustrate the problem.

Then, I would like to create my test object which contains the function reference wrapper:

struct test {
    wrapper myWrapper;
    
    test() : myWrapper{std::bind(&test::boom, this)}{};
    
    void boom() {
        std::cout << "boom()" << std::endl;
    }
    
};

At test object instanciation, I get the following error (try yourself here ):

 cannot bind non-const lvalue reference of type 'std::function<void()>&' to an rvalue of type 'std::function<void()>'

It is understandable, since the std::bind object is a temporary (rvalue) for which I cannot take a reference (I also tried my way without std::bind , without better results). On the other hand, being able to take a reference to a non-static member function as a std::function seems like something easy to do, but I can't wrap my head around it.

Is there any simple way to take a reference to a non-static member function as a std::function& ?

With this "raw" implementation of "typed bind" I can ask: Where the memory that holds "test*" pointer would be stored by wrapper? And how bindex would know wich type sould be converted in where call ->first? Should this bindex be type erased?

struct bindx : pair<void(test::*)(void), test*> {
    using pair<void(test::*)(void), test*>::pair;
    void operator()() { (second->*first)(); }
};

struct wrapper {
    bindx f_;
    
    wrapper(bindx f) : f_{f}{
        f_();    
    };
};

struct test {
    wrapper myWrapper;
    
    test() : myWrapper( bindx{&test::boom, this} ) {};
     . . .
}

http://coliru.stacked-crooked.com/a/a40f432aad928908

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