如何将成员函数指针传递给模板函数中的重载方法?
我提到了这个有点类似的问题。但这里的情况有所不同:
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
那么代码就可以正常工作。但对于重载情况,编译器会抱怨:
错误:没有匹配的调用函数 到 `ReceiveFuncPtr(A&, [未解决 重载函数类型])'
有什么方法可以在调用 ReceiveFuncPtr()
时进行显式类型转换,而不是在其 template
参数中进行一些更改并使其能够接收< code>foo(int) 版本始终适用于任何类似的 class A
?
编辑:想法是在调用函数时不用担心类型。它应该像 ReceiveFuncPtr(obj, &A::foo);
一样简单,并让 template
完成其工作。
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, ReceiveFuncPtr(obj, &A::foo);
And let the template
do its work.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这个怎么样:
how about this:
您可以将函数模板编写为:
该函数模板将自动选择
void foo (int i)
。我之前的回答(不删除它,因为它可能对其他人有帮助):
你的问题:
你可以这样做:
pFun
是一个指向void A::的指针f(int)
您还可以将 typedef 用作:
You can write the function template as:
This function template will automatically choose
void foo (int i)
.My previous answer (not deleting it, as it maybe helpful for others):
Your problem:
You can do this:
pFun
is a pointer tovoid A::f(int)
You can also use typedef as: