代码之家  ›  专栏  ›  技术社区  ›  Carl Seleborg

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

  •  18
  • Carl Seleborg  · 技术社区  · 15 年前

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

    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”——这就是公认的答案所指出的。不过,我还是不提这个问题,因为我认为这个问题可能会发生在其他人身上。

    1 回复  |  直到 13 年前
        1
  •  27
  •   Johannes Schaub - litb    15 年前

    好吧,我会回答我已经发表的评论,这样它就可以被接受了。问题在于常量:

    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)。他实际上把它作为一个常量成员函数,并告诉我应该把它作为一个答案发布。