我提到了这个somewhat similar question .但是这里的情况不同:
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
}
在上面的测试代码中,我在A
中重载了一个foo
。如果只有 1 个 foo
那么代码就可以正常工作。但是对于重载情况,编译器会提示:
error: no matching function for call to `ReceiveFuncPtr(A&, [unresolved overloaded function type])'
除了在调用 ReceiveFuncPtr()
时进行显式类型转换之外,有什么方法可以让我们对其 template
参数进行一些更改并使其能够接收 foo (int)
version always for any similar class A
?
编辑:想法是在调用函数时不要担心类型。它应该像 ReceiveFuncPtr(obj, &A::foo);
一样简单,让 template
完成它的工作。
最佳答案
这个怎么样:
template<typename ObjType>
void ReceiveFuncPtr (ObjType o, void (ObjType::*pf)(int))
{
(o.*pf)(1);
}
关于c++ - 如何将成员函数指针传递给模板函数中的重载方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6381524/