【问题标题】:Passing method as templated argument C++11将方法作为模板化参数传递 C++11
【发布时间】:2018-11-24 10:23:28
【问题描述】:

我有这个结构:

class A {
  public:
     int setI(int i){_i = i;}
  private:
     int _i;
}
class B {
  public:
     int setZ(int z){_z = z;}
  private:
     int _z;
}
class C : public A, public B {};

然后我想从其他地方的模板函数调用方法 setI 或 setZ

类似:

template <class P>
void myMethod(P &myclass, void (P::*setter) (const int)) const
   {
         int var = 9;
         (myclass.*setter)(var);
   }

我是这样使用这种方法的:

   C c;
   mymethod(c, &C::setI); 

因为 setI 是在 A 中而不是在 C 中定义的,所以它失败了,有没有办法按照这个结构从 A 类或 B 类传递方法?

感谢和问候

【问题讨论】:

    标签: c++ c++11 templates parameter-passing


    【解决方案1】:

    它失败的部分原因是C::setIprotected。通过设置C::setI public 使其可以访问该代码段。

    另一部分是void(P::*setter)(const int) 不是C::setI 的类型。应该是int(P::*setter)(int)

    或者,将 lambda 传递给myMethod,这样您就不必拼写成员函数指针类型,而且效率更高:

    template<class P, class Setter>
    void myMethod(P &myclass, Setter set) {
        int var = 9;
        set(myclass, var);
    }
    
    int main() {
        C c;
        myMethod(c, [](C& c, int a) { c.setI(a); }); 
    }
    

    您可能还希望启用警告(-Wall -Wextra -Werror 用于 gccclang)以便在函数忘记返回值时编译失败,例如 setIsetZ 这样做。

    【讨论】:

    • 谢谢,我将修改示例,因为事件将两个设置器都设置为公共失败
    • @RuLoViC 为您更新了答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-30
    • 2018-09-09
    • 1970-01-01
    • 1970-01-01
    • 2016-04-21
    相关资源
    最近更新 更多