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

发布于 2024-07-16 08:46:05 字数 602 浏览 7 评论 0原文

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

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

失去的东西太少 2024-07-23 08:46:05

好吧,我会回答我已经发表的评论,以便它可以被接受。 问题在于 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 成员函数,并告诉我应该将其发布为答案。

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;
  }
};

Clarification:

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文