get function ptr to member function of instanced class?
-
13-10-2019 - |
Question
class gfx {
void resize(int x, int y);
}
gfx g;
can i cast g.resize to a 'void (*)(int, int)' somehow?
Solution
No. gfx::resize
is of type void(gfx::*)(int, int)
. You can't meaningfully convert it to type void(*)(int, int)
because you can only call it as a member function on an object of type gfx
.
A member function can only be called on an instance of the class, so given your gfx g;
, you can call g.resize()
, but you can't just call resize()
like it were an ordinary function. An ordinary function pointer can't point to a member function because it doesn't have any way to bind the function call to an instance of the class.
Conceptually, a member function takes an additional parameter, the this
parameter, that points to the instance of the class on which it was called.
If you want to be able to call a member function via an ordinary function pointer, you can create a nonmember function (or a static member function) wrapper with a parameter to which you can pass the instance of the object on which to call the member function. For example, you could have:
void resize(gfx* obj, int x, int y) {
return obj->resize(x, y);
}
This nonmember resize
function has type void(*)(gfx*, int, int)
and can be called as a nonmember function. The generalized form of this approach is the std::function
and std::bind
facilities found in C++0x (you can also find them in Boost and in C++ TR1).
OTHER TIPS
Yes, you can do it:
void easy_resize(int x, int y) { g.resize(x, y); }