如何获取重载成员函数的地址? [英] How to get the address of an overloaded member function?
问题描述
我试图获取指向特定版本的重载成员函数的指针。例如:
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
}
};
错误消息是error C2440:'initializing':无法从'overloaded-function' 'MemberFunctionType'
The error message is "error C2440: 'initializing' : cannot convert from 'overloaded-function' to 'MemberFunctionType'"
如果 f
没有重载,任何建议?
This works if f
is not overloaded, but not in the example above. Any suggestion?
请注意,上述代码并未反映出我的现实问题,我忘了一个常量 - 这是接受的答案指出。我会离开这个问题,因为我认为这个问题可能发生在别人身上。
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.
推荐答案
我会回答我所作的评论,所以它可以接受。问题是与constness:
Well, i'll answer what i put as comment already so it can be accepted. Problem is with constness:
class C
{
bool f(int) { ... }
bool f(double) const { ... }
bool example()
{
// I want to get the "double" version.
typedef bool (C::*MemberFunctionType)(double) const; // const required!
MemberFunctionType pointer = &C::f;
}
};
澄清:
原始问题不包含 const
。我在评论中做了一个疯狂的猜测,他是否可能有 f
作为一个const成员函数在真正的代码(因为在一个更早的迭代,结果还是另一件事缺少/不同于真实世界的代码:p)。他实际上是一个const成员函数,并告诉我,我应该发布为一个答案。
The original question didn't contain that const
. I did a wild guess in the comments whether he possibly has f
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.
这篇关于如何获取重载成员函数的地址?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!