Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get a pointer to object's member function

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*); 
like image 671
Alex Hoppus Avatar asked Jan 14 '12 22:01

Alex Hoppus


People also ask

How do you get a pointer to member function?

The pointer to member operators . * and ->* are used to bind a pointer to a member of a specific class object. Because the precedence of () (function call operator) is higher than . * and ->* , you must use parentheses to call the function pointed to by ptf .

Is it possible to create a pointer to member function of any class?

Pointers to members allow you to refer to nonstatic members of class objects. You cannot use a pointer to member to point to a static class member because the address of a static member is not associated with any particular object.

How do you pass this pointer to a function in C++?

Passing Pointers to Functions in C++ C++ allows you to pass a pointer to a function. To do so, simply declare the function parameter as a pointer type.


1 Answers

You cannot, at least it won't be only a pointer to a function.

Member functions are common for all instances of this class. All member functions have the implicit (first) parameter, this. In order to call a member function for a specific instance you need a pointer to this member function and this instance.

class Some_class { public:     void some_function() {} };  int main() {     typedef void (Some_class::*Some_fnc_ptr)();     Some_fnc_ptr fnc_ptr = &Some_class::some_function;      Some_class sc;      (sc.*fnc_ptr)();      return 0; } 

More info here in C++ FAQ

Using Boost this can look like (C++11 provides similar functionality):

#include <boost/bind.hpp> #include <boost/function.hpp>  boost::function<void(Some_class*)> fnc_ptr = boost::bind(&Some_class::some_function, _1); Some_class sc; fnc_ptr(&sc); 

C++11's lambdas:

#include <functional>  Some_class sc; auto f = [&sc]() { sc.some_function(); }; f(); // or auto f1 = [](Some_class& sc) { sc.some_function(); }; f1(sc); 
like image 114
Andriy Tylychko Avatar answered Sep 30 '22 21:09

Andriy Tylychko