简体   繁体   中英

Getting object that contains the member function from boost function created with bind

void someFunction(boost::function<void()> func)
{
    ... //Get myObj
}
MyClass *myObj = ...;
someFunction(boost::bind(&MyClass::memberFunction, myObj));

How can I get pointer or reference to myObj from inside the function void someFunction

Generally it is not possible nor desirable to extract the object used as an argument to boost::bind (or std::bind ) back from the result of the bind. The way the resulting object is stored is implementation specific.

Observe how it is defined as unspecified in the documentation (see link below):

// one argument
template<class R, class F, class A1> unspecified-3 bind(F f, A1 a1);

To illustrate further, take a look at this paragraph, on the same page:

The function objects that are produced by boost::bind do not model the STL Unary Function or Binary Function concepts, even when the function objects are unary or binary operations, because the function object types are missing public typedefs result_type and argument_type or first_argument_type and second_argument_type. In cases where these typedefs are desirable, however, the utility functionmake_adaptable can be used to adapt unary and binary function objects to these concepts.

http://www.boost.org/doc/libs/1_55_0/libs/bind/bind.html#CommonDefinitions

The library developers explicitly tell you that the type that's returned is opaque, won't give you back the type of the arguments you've passed in, and don't intend for you to obtain the objects from within the opaque bind return type.

However, when you call bind() it is you who supplies the argument, so you can just store them aside and use them later. Alternatively, as suggested in the comments you can just use *this as a reference to the callee when the bound method is invoked.

#include <boost/bind.hpp>
#include <iostream>

struct Foo {
    void f() const {
       const Foo& myObj = *this;
       std::cout << "Invoked  instance: " << std::hex << &myObj << std::endl;
    }
};

int main() {
    Foo foo;
    std::cout << "Invoking instance: " << std::hex << &foo << std::endl;
    boost::bind(&Foo::f, boost::ref(foo))();
    return 0;
}
/* Output:
Invoking instance: 0x7fff4381185f
Invoked  instance: 0x7fff4381185f */

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