如何将方法作为函数参数传递?

时间:2019-03-14 17:00:20

标签: function c++11 methods arguments

我有下面的代码,但无法编译,告诉我: “错误:无效使用非静态成员函数”。 有没有一种方法可以将这样的方法作为函数参数传递而不会使其变为静态?

class Base{
public:
    virtual int method() = 0;
}

class Derived1: public Base{
public:
    int method(){ return num; }
private:
    int num;
}

class Derived2: public Base{
public:
    int method(){ return dif_num; }
private:
    int dif_num;
}

template <class T>
int func( T obj, int(*f)() ){
    std::cout<<obj->f()<<std::endl;
}




int main(){
    Derived1* obj = new Derived1();
    func( obj, obj->method/*????*/ )
}

谢谢!

1 个答案:

答案 0 :(得分:0)

  1. 不要使用函数指针。请改用std::function
  2. 在对func的调用中使用lambda表达式。编译器会将其转换为std::function


template <class T>
int func( T obj, std::function<int()>f ){
    std::cout<<obj->f()<<std::endl;
}

int main(){
    Derived1* obj = new Derived1();
    func( obj, [obj]() -> int {return obj->method();} )
}