Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning pointer-to-member-function (without typedefs)

Compiling on C++03, I've attempted to write up a test template function that returns a pointer-to-member-function of a member function that returns int, and takes two float arguments:

template<typename TemplateClass>
int (TemplateClass::*)(float,float) Testtest(TemplateClass &A)
{
    return &TemplateClass::Function;
}

But naturally, no matter what variations on the pointer-to-member-function syntax I use, the compiler complains of initialisation errors. Typedef, although it works with known classes, for obvious reasons (naming conflicts), won't accept template class arguments for classes that I can't know ahead of time which are likely to use the same function.

What non-typedef way is there to get this function to compile and return a pointer-to-member-function?

like image 576
c1646091 Avatar asked May 17 '16 09:05

c1646091


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 return of pointer from a function?

We can pass pointers to the function as well as return pointer from a function. But it is not recommended to return the address of a local variable outside the function as it goes out of scope after function returns.

Why can't the this pointer be used in non member functions?

The 'this' pointer is passed as a hidden argument to all nonstatic member function calls and is available as a local variable within the body of all nonstatic functions. 'this' pointer is not available in static member functions as static member functions can be called without any object (with class name).


2 Answers

To declare it without a type alias, without type deduction, and without a trailing return type:

template<typename TemplateClass>
int (TemplateClass::* Testtest(TemplateClass &A))(float,float)

But of course this isn't what you would use in real code. Instead you would use an alias template:

template<typename T>
using return_type = int (T::*)(float,float);

template<typename TemplateClass>
return_type<TemplateClass> Testtest(TemplateClass &A)

Or return type deduction in C++14:

template<typename TemplateClass>
auto Testtest(TemplateClass &A)

Or a trailing return type (in C++11):

template<typename TemplateClass>
auto Testtest(TemplateClass &A) -> int (TemplateClass::*)(float,float)
like image 144
emlai Avatar answered Oct 16 '22 10:10

emlai


You need this prototype:

template<typename TemplateClass>
int (TemplateClass::*Testtest(TemplateClass &A)) (float,float) { }
like image 3
Holt Avatar answered Oct 16 '22 09:10

Holt