我正在尝试获取指向重载成员函数的特定版本的指针。示例如下:
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
}
};
错误消息是“错误函数:‘初始化’:无法从‘C2440-C2440’转换为'MemberFunctionType'”
如果f
没有重载,这是可行的,但在上面的示例中不是这样。有什么建议吗?
编辑
注意,上面的代码没有反映我的真实问题,即我忘记了一个"const“--这是公认的答案所指出的。不过,我会让问题保持原样,因为我认为这个问题可能会发生在其他人身上。
发布于 2009-04-01 15:05:59
好吧,我会回答我已经放在评论中的东西,这样它就可以被接受了。问题出在稳定性上:
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
作为真实代码中的常量成员函数(因为在更早的迭代中,它还缺少/不同于现实世界代码的另一件事:p)。他实际上是一个常量成员函数,并告诉我应该把这个作为答案发布。
https://stackoverflow.com/questions/705854
复制相似问题