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