如何将成员函数指针传递给模板函数中的重载方法? [英] How to pass a member function pointer to an overloaded method in a template function?
问题描述
我提到了这个有些类似的问题.但是这里的情况有所不同:
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
}
在上面的测试代码中,我在A
中有一个重载的foo
.如果只有 1 个 foo
那么代码工作正常.但是对于重载的情况,编译器会抱怨:
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:
错误:没有匹配的调用函数到 `ReceiveFuncPtr(A&, [未解析重载函数类型])'
error: no matching function for call to `ReceiveFuncPtr(A&, [unresolved overloaded function type])'
不是在调用 ReceiveFuncPtr()
时显式类型转换,我们有什么方法可以对其 template
参数进行一些更改并使其能够接收 foo(int)
版本总是用于任何类似的 class A
?
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
?
编辑:想法是在调用函数时不要担心类型.它应该很简单,ReceiveFuncPtr(obj, &A::foo);
让 template
完成它的工作.
Edit: Idea is not to worry about the type while calling the function. It should be as simple as, ReceiveFuncPtr(obj, &A::foo);
And let the template
do its work.
推荐答案
这个怎么样:
template<typename ObjType>
void ReceiveFuncPtr (ObjType o, void (ObjType::*pf)(int))
{
(o.*pf)(1);
}
这篇关于如何将成员函数指针传递给模板函数中的重载方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!