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?
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 .
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.
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).
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)
You need this prototype:
template<typename TemplateClass>
int (TemplateClass::*Testtest(TemplateClass &A)) (float,float) { }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With