Here is the problem:
1) I have a class like so:
class some_class
{
public:
some_type some_value;
int some_function(double *a, double *b, int c, int d, void *e);
};
2) Inside some_function
, I use some_values
from some_class
object to get a result.
3) So, I have a concrete object and I want to get a pointer to this object some_function
.
Is it possible? I can't use some_fcn_ptr
because the result of this function depends on the concrete some_value
of an object.
How can I get a pointer to some_function
of an object? Thanks.
typedef int (Some_class::*some_fcn_ptr)(double*, double*, int, int, void*);
You may write some kind of Wrapper which is able to use both function or method as parameter.
I used following classes for launching functions (it was used in one my SDL program):
And this extension for "methods":
And then use it as:
I found macro as this:
really useful
I used the Boost library. I included "boost/bind.hpp" in my code. Then a method named "fn" can be defined as
auto fn = boost::bind(ClassName::methodName, classInstanceName, boost::placeholders::_1);
You cannot, at least it won't be only a pointer to a function.
Member function is common for all instances of this class. All member functions have implicit (first) parameter -
this
. To call a member function for specific instance you need pointer to this member function and this instance.More info here in C++ FAQ
Using Boost this can look like (C++11 provides similar functionality):
C++11's labdas:
No, you can't get a pointer to a C++ class method (unless the method is declared static). The reason is that a class method always has the pointer
this
, a pointer to the class instance. But were you to call the method through a pointer, that pointer could not encapsulate thethis
pointer, and then then there would be no instance attached, and therefore this behavior is not legal.While not exactly what you requested, if you can use C++11 the following might nevertheless suit your needs (untested):