0
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?

1
  • Where do you want to access func's internals from? Is it from within the same scope in which func is defined, or is it from within the scope of the function func is passed on to? Commented May 16, 2012 at 10:51

3 Answers 3

4

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.