Search code examples
c++c++03member-functionspointer-to-member

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?


Solution

  • 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)