如何获取重载成员函数的地址?
我正在尝试获取指向重载成员函数的特定版本的指针。 示例如下:
class C
{
bool f(int) { ... }
bool f(double) { ... }
bool example()
{
// I want to get the "double" version.
typedef bool (C::*MemberFunctionType)(double);
MemberFunctionType pointer = &C::f; // <- Visual C++ complains
}
};
错误消息为“error C2440: 'initializing' :无法从 'overloaded-function' 转换为 'MemberFunctionType'”
如果 f
未重载,则此方法有效,但在上面的示例中无效。 有什么建议吗?
编辑
请注意,上面的代码没有反映我的现实问题,即我忘记了一个“const” - 这就是公认的答案所指出的。 不过,我将保留这个问题,因为我认为这个问题也可能发生在其他人身上。
I'm trying to get a pointer to a specific version of an overloaded member function. Here's the example:
class C
{
bool f(int) { ... }
bool f(double) { ... }
bool example()
{
// I want to get the "double" version.
typedef bool (C::*MemberFunctionType)(double);
MemberFunctionType pointer = &C::f; // <- Visual C++ complains
}
};
The error message is "error C2440: 'initializing' : cannot convert from 'overloaded-function' to 'MemberFunctionType'"
This works if f
is not overloaded, but not in the example above. Any suggestion?
EDIT
Beware, the code above did not reflect my real-world problem, which was that I had forgotten a "const" - this is what the accepted answer points out. I'll leave the question as it is, though, because I think the problem could happen to others.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
好吧,我会回答我已经发表的评论,以便它可以被接受。 问题在于 constness:
澄清:
原始问题不包含该
const
。 我在评论中做了一个疯狂的猜测,他是否可能在真实代码中将f
作为 const 成员函数(因为在更早的迭代中,事实证明还有另一件事丢失/与真实代码不同) -世界代码:p)。 他实际上将其作为 const 成员函数,并告诉我应该将其发布为答案。Well, i'll answer what i put as comment already so it can be accepted. Problem is with constness:
Clarification:
The original question didn't contain that
const
. I did a wild guess in the comments whether he possibly hasf
being a const member function in the real code (because at a yet earlier iteration, it turned out yet another thing was missing/different to the real-world code :p). He actually had it being a const member function, and told me i should post this as an answer.