How can I access class instance(object) pointer in "boost::function"?

738 views Asked by At
CClass inst;
boost::function<bool(int)> func = boost::bind(&CClass::Foo, &inst, _1);

In this situation, I want to access inst's pointer(&inst) or address from "func" like below.

CClass* pInstance = func.obj_ptr; (This is just a form that I want)

How can I do?

3

There are 3 answers

0
Arpegius On BEST ANSWER

There is a way, with the use of boost::function::target() template method. But since boost::bind return unspecified type, witch do not yet provide a way to access arguments, you will need to write your own binder functor. Here is some example:

class MyClass
{
    public:
    void myMethod()
    {
        std::cout << "This is my Method" << std::endl; 
    }
};

struct MyFunctor
{
    MyFunctor(MyClass* o, void (MyClass::*m)()): object(o),method(m){}
    MyClass* object;
    void (MyClass::*method)();

    void  operator() ()
    {
        return (object->*method)();
    }
};

So now you can access:

MyClass myObject;
boost::function< void() > func= MyFunctor(&myObject, &MyClass::myMethod);
func();

assert( func.target<MyFunctor>()->object == &myObject );

Same as with the boost::any there is no way to have polymorphic access witch the target template method.

0
Greg On

I guess that such member (argument) should be not public within boost::function class. If I am right, you won't be able to do it. At least without some strange operations.

If you really need something similar and are creator of func objects, the most clean way I can imagine right now is: std::pair<boost::function<bool(int)>, CClass *> funcAndObj, then call funcAndObj.first() and get the pointer from funcAndObj.second.

0
Nicol Bolas On

You cannot. The whole point of boost/std::function is to erase the type that was stored within it. To implement what you're talking about would require re-constituting the type. And since C++ is a statically-typed language, that means the code that calls such a function would have to explicitly provide the type being returned. Something like func.value<TypeName>().

Even moreso, what you're talking about wouldn't be possible even if that were available. The only type that function knows about is the type it was given. Which is the return value from boost/std::bind. That type is not widely available without digging into the implementation specifics.

So what you're asking for is not possible. Not without storing it elsewhere yourself.