【问题标题】:Resolve const and non-const member function pointer解析 const 和非 const 成员函数指针
【发布时间】:2019-10-10 03:58:53
【问题描述】:

在下面的代码sn-p中,我希望能够从doWork调用A::foo

但是,由于foo 有两个重载(const 和非const),编译器无法解析我在调用doWork 时的意思。 有没有办法告诉编译器我的意思是哪个。

我无法更改struct A

我可以在 doWork 的签名或 doWork 的调用中做一些事情来总是选择说 const 吗?

我知道的一个解决方案是将函数指针类型作为doWork 的参数而不是模板(像这样) void doWork(void (A::*fun)(void) const){ 但这有点难看,我希望找到一个基于模板的解决方案(如果存在的话)

struct A{
    void foo() const {
    }
    void foo(){
    }
    void bar(){
    }
    void bar() const {
    }
};

template<typename F>
void doWork(F fun){
    const A a;
    (a.*fun)();
}

int main()
{
    doWork(&A::foo); //error: no matching function for call to ‘doWork()’
    doWork(&A::bar); // error: no matching function for call to ‘doWork()’
    return 0;
}

【问题讨论】:

    标签: c++ member-function-pointers


    【解决方案1】:

    您可以使用static_cast 指定应该使用哪一个。

    static_cast 也可用于消除函数重载的歧义 执行到特定类型的函数到指针转换,如

    std::for_each(files.begin(), files.end(),
                  static_cast<std::ostream&(*)(std::ostream&)>(std::flush));
    

    例如

    doWork(static_cast<void (A::*)(void) const>(&A::foo));
    doWork(static_cast<void (A::*)(void) const>(&A::bar));
    

    或者明确指定模板参数。

    doWork<void (A::*)(void) const>(&A::foo);
    doWork<void (A::*)(void) const>(&A::bar);
    

    【讨论】:

      【解决方案2】:

      您可以使用:

      template <typename T>
      void doWork(void (T::*fun)() const){
          const A a;
          (a.*fun)();
      }
      

      更通用的函数模板将使用const T a

      template <typename T>
      void doWork(void (T::*fun)() const){
          const T a;
          (a.*fun)();
      }
      

      请注意,第二个版本不会在任何地方假定A

      【讨论】:

      • 接受了这个答案,因为这让doWork更干净。
      猜你喜欢
      • 2016-08-17
      • 2014-10-18
      • 2017-03-19
      • 2011-03-04
      • 2010-12-26
      • 2016-02-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多