Returning a pointer to a function element (without typedefs)

Compiling in C ++ 03, I tried to write a test template function that returns a member function, a member function that returns an int, and takes two float arguments:

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

But, of course, no matter what variations in the pointer-member-function syntax I use, the compiler complains about initialization errors. Typedef, although it works with well-known classes for obvious reasons (name conflicts), will not accept template class arguments for classes that I cannot know in advance that can use the same function.

What way should a non-typedef get this function to compile and return a member function?

+6
source share
4 answers

To declare it without a type alias, without type inference, and without return type:

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

But of course, this is not what you would use in real code. Instead, you should use an alias template :

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

Or output type return in C ++ 14:

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

Or returning return type (in C ++ 11):

 template<typename TemplateClass> auto Testtest(TemplateClass &A) -> int (TemplateClass::*)(float,float) 
+5
source

You need this prototype:

 template<typename TemplateClass> int (TemplateClass::*Testtest(TemplateClass &A)) (float,float) { } 
+3
source
  int (Class::*f())(float,float); 

f is a function with no arguments that return a pointer to a member function of the Class takinf 2 floats class and returns an int.

And the template version:

  template <typename Type> int (Type::*f())(float,float); 
+2
source

I reject the assumption of your question. Use typedefs. Or, in particular, a type trait:

 template <class T, class F> struct make_mem_fun { typedef FT::*type; }; template<typename TemplateClass> typename make_mem_fun<TemplateClass, int(float, float)>::type Testtest(TemplateClass &A) { return &TemplateClass::Function; } 

This is easier to understand than the complex syntax of the actual type return. With C ++ 11, we can turn this into an alias to remove typename ::type stuff.

0
source

All Articles