开发者

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

开发者 https://www.devze.com 2023-03-13 10:03 出处:网络
I referred to this somewhat similar question. However here the scenario is different: struct A { void foo (int i) {} // choice

I referred to this somewhat similar question. However here the scenario 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. Had there been only 1 foo then the code works fine. But for overloading case, compiler complains as:

error: no matching function for call to `ReceiveFuncPtr(A&, [unresolved overloaded function type])'

Instead of explicit typecasting while calling ReceiveFuncPtr(), is there any way that we can make some changes in its template parameter and enable it to receive foo(int) version always for any similar class A ?

Edit: Idea is not to worry about the type while calling the function. It should be as simple as, Rece开发者_StackOverflow中文版iveFuncPtr(obj, &A::foo); And let the template do its work.


how about this:

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


You can write the function template as:

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

This function template will automatically choose void foo (int i).


My previous answer (not deleting it, as it maybe helpful for others):

Your problem:

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

You can do this:

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 as:

typedef void (A::*FunDouble)(double);
typedef void (A::*FunInt)(int);

FunInt pFun  = &A::foo;    // No casting here!
ReceiveFuncPtr(obj, pFun); // No casting here!
0

精彩评论

暂无评论...
验证码 换一张
取 消