Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

member function pointer which returns same type of member function pointer

I'd like to declare a member function pointer in C++, that returns the same member function pointer type

This doesn't work:

class MyClass { 
public: 
        typedef FunctionPtr (MyClass::*FunctionPtr)(); 
}

Does someone know a solution?

like image 587
Frank28 Avatar asked Jul 02 '10 20:07

Frank28


People also ask

Which pointer is used in 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 .

Can we call member function using this pointer?

Function pointer to member function in C++ In C++ , function pointers when dealing with member functions of classes or structs, it is invoked using an object pointer or a this call. We can only call members of that class (or derivatives) using a pointer of that type as they are type safe.

Is function pointer and function pointer same?

They're synonymous - "a function pointer" and "a pointer to a function" describe an object that can hold the address of a function.

Can we declare a function that can return a pointer to a function of the same type?

You cannot return a function in C - you return a pointer to a function. If you mean to define a function which returns a pointer to a function which again returns a pointer to a function and so on, then you can use typedef to implement it.


1 Answers

There's no way to achieve exactly that. In fact, member functions make no difference here: there's no way to declare an ordinary function that returns a pointer to its own function type. The declaration would be infinitely recursive.

In case of an ordinary function you can use the void (*)() type as an "universal" function pointer type (just like void * is often used for data types). For member function pointers that would be void (A::*)() type. You'd have to use reinterpret_cast for that purpose though. However, this usage (a round-trip conversion) happens to be the one when the behavior of reinterpret_cast is defined.

Of course, you'll be forced to use casts to convert the pointer to and from that type. AFAIK, there are elegant template-based solutions with an intermediate temporary template object that does the casting.

You might also want to take a look at this GotW entry.

P.S. Note, that using void * type as an intermediate type for function pointers is prohibited by the language. While such illegal use might appear to be "working" with ordinary function pointers, it has absolutely no chance to work with member function pointers. Member function pointers are normally non-trivial objects with size greater than the size of void * pointer.

like image 129
AnT Avatar answered Sep 26 '22 02:09

AnT