How to best pass methods into methods of the same class

前端 未结 3 1502
你的背包
你的背包 2021-01-02 16:40

I have this C++ class that one big complicated method compute that I would like to feed with a \"compute kernel\", a method of the same class. I figure I would

3条回答
  •  温柔的废话
    2021-01-02 17:29

    You have two alternatives :

    1. using pointer to member function
    2. using lambda functions

    Example using pointer to member function :

    #include 
    
    class D
    {
    public:
      D(int v ) : classVar_(v){}
      int add_(int a, int b){return (a+b+classVar_);}
      int multiply_(int a, int b){return (a*b+classVar_);}
    private:
      int classVar_;
    };
    
    class test {
    public:
    
    int compute_(int a, int b, D &d, int (D::*f)(int a, int b))
    {
       int c=0;
       // Some complex loops {
       c += (d.*f)(a,b);
       // }
       return c;
    }
    
    };
    
    int main()
    {
      test test;
      D d(1);
    
      std::cout<<"add : " << test.compute_( 5, 4, d, &D::add_ ) << std::endl;
      std::cout<<"add : " << test.compute_( 5, 4, d, &D::multiply_ ) << std::endl;
    }
    

    Example using lambda :

    #include 
    #include 
    
    class D
    {
    public:
      D(int v ) : classVar_(v){}
      int add_(int a, int b){return (a+b+classVar_);}
      int multiply_(int a, int b){return (a*b+classVar_);}
    private:
      int classVar_;
    };
    
    class test {
    public:
    
    int compute_(int a, int b, std::function< int(int,int) > f)
    {
       int c=0;
       // Some complex loops {
       c += f(a,b);
       // }
       return c;
    }
    
    };
    
    int main()
    {
      test test;
      D d(1);
    
      std::cout<<"add : " << test.compute_( 5, 4, [&d](int a, int b){ return d.add_(a,b); } ) << std::endl;
      std::cout<<"add : " << test.compute_( 5, 4, [&d](int a, int b){ return d.multiply_(a,b); } ) << std::endl;
    }
    

提交回复
热议问题