gpt4 book ai didi

c++ - 如何获取重载成员函数的地址?

转载 作者:IT老高 更新时间:2023-10-28 22:02:34 26 4
gpt4 key购买 nike

我正在尝试获取指向重载成员函数的特定版本的指针。示例如下:

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' : cannot convert from 'overloaded-function' to 'MemberFunctionType'”

如果 f 没有重载,则此方法有效,但在上面的示例中没有。有什么建议吗?

编辑

请注意,上面的代码并未反射(reflect)我的实际问题,即我忘记了“const” - 这是公认的答案所指出的。不过,我会保留这个问题,因为我认为这个问题可能会发生在其他人身上。

最佳答案

好吧,我会回答我已经发表的评论,以便可以接受。问题在于常量:

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 成员函数,并告诉我应该将其发布为答案。

关于c++ - 如何获取重载成员函数的地址?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/705854/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com