Member function pointer that returns the same type of member function pointer

I would like to declare a member function pointer in C ++ that returns the same type of member function pointer

This does not work:

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

Does anyone know a solution?

+7
c ++ declaration return-type
source share
3 answers

There is no way to achieve just that. Actually, member functions do not matter here: there is no way to declare a regular function that returns a pointer to its own type of function. An ad will be infinitely recursive.

In the case of a regular function, you can use the void (*)() type as a universal type of function pointer (just like void * often used for data types). For pointers to member functions that will be void (A::*)() . However, for this you need to use reinterpret_cast . However, this use (round-trip conversion) is when reinterpret_cast behavior is defined.

Of course, you will be forced to use casts to convert the pointer to and from this type. AFAIK, there are elegant template solutions with an intermediate temporary template that performs casting.

You can also take a look at this GotW post .

PS Please note that the use of the void * type as an intermediate type for function pointers is prohibited by the language. Although such illegal use may seem β€œworking” with ordinary function pointers, it has absolutely no way to work with member function pointers. Function-function pointers are usually nontrivial objects with a size larger than the size of the void * pointer.

+5
source share

AndreyT cites the best answer on GotW # 57 , so I could also reproduce it here:

 class MyClass { public: struct FunctionPtrProxy; typedef FunctionPtrProxy (MyClass::*FunctionPtr)(); struct FunctionPtrProxy { FunctionPtrProxy(FunctionPtr pp ) : p( pp ) { } operator FunctionPtr() { return p; } FunctionPtr p; } } 
+5
source share

What you are trying to do is impossible - the return type of the function is the type of the function itself, which is not yet known, so it leads to an infinite loop.

0
source share

All Articles