How do I pass a member function pointer to an overloaded method in a template function?

I called this somewhat similar question . However, the scenario here is different:

struct A { void foo (int i) {} // choice void foo (double i) {} }; template<typename ObjType, typename FuncPtr> void ReceiveFuncPtr (ObjType o, FuncPtr pf) { (o.*pf)(1); } int main () { A obj; ReceiveFuncPtr(obj, &A::foo); // don't want typecast here } 

In the above test code, I have an overloaded foo inside A If there was only 1 foo , then the code worked fine. But for the case of overload, the compiler complains like:

error: there is no corresponding function to call on `ReceiveFuncPtr (A &, [unresolved overloaded function type]) '

Instead of explicit type casting when calling ReceiveFuncPtr() there a way to make some changes to its template parameter and let it always get the foo(int) version for any such class A ?

Change The idea is not to worry about type when calling a function. It should be as simple as ReceiveFuncPtr(obj, &A::foo); And let template do its job.

+2
source share
2 answers

how about this:

 template<typename ObjType> void ReceiveFuncPtr (ObjType o, void (ObjType::*pf)(int)) { (o.*pf)(1); } 
+4
source

You can write a function template as:

 template<typename ObjType> void ReceiveFuncPtr (ObjType o, void (ObjType::*pf)(int) ) { (o.*pf)(1); } 

This function template automatically selects void foo (int i) .


My previous answer (without deleting it, as it may be useful to others) :

Your problem:

 ReceiveFuncPtr(obj, &A::foo); // don't want typecast here 

You can do it:

 void (A::*pFun)(int) = &A::foo; // No casting here! ReceiveFuncPtr(obj, pFun); // No casting here! 

pFun is a pointer to void A::f(int)


You can also use typedef like:

 typedef void (A::*FunDouble)(double); typedef void (A::*FunInt)(int); FunInt pFun = &A::foo; // No casting here! ReceiveFuncPtr(obj, pFun); // No casting here! 
+4
source

All Articles