c++ passing class method as argument to a class method with templates

无人久伴 提交于 2019-12-11 12:22:30

问题


I'm trying to pass a class method to another class method using template, and cannot find any answer on how to do (no C++11, boost ok):

I simplified the core problem to :

class Numerical_Integrator : public Generic Integrator{
    template <class T>
    void integrate(void (T::*f)() ){
         // f(); //already without calling  f() i get error
    }
}

class Behavior{
    void toto(){};

    void evolution(){
        Numerical_Integrator my_integrator;
        my_integrator->integrate(this->toto};
}

I get as error:

error: no matching function for call to ‘Numerical_Integrator::integrate(<unresolved overloaded function type>)’this->toto);
note:   no known conversion for argument 1 from ‘<unresolved overloaded function type>’ to ‘void (Behavior::*)()’

Thank you.

Bonus: What about with arguments ?

class Numerical_Integrator{
    template <class T, class Args>
    double integrate(void (T::*f)(), double a, Args arg){
         f(a, arg);
    }
}

class Behavior{
    double toto(double a, Foo foo){ return something to do};

    void evolution(){
     Foo foo;
     Numerical_Integrator my_integrator;
     my_integrator->integrate(this->toto, 5, foo};
}

回答1:


Your question is not really about passing a class method as part of a template parameter.

Your question is really about correctly invoking a class method.

The following non-template equivalent will not work either:

class SomeClass {

public:

     void method();
};

class Numerical_Integrator : public Generic Integrator{
    void integrate(void (SomeClass::*f)() ){
         f();
    }
}

A class method is not a function, and it cannot be invoked as a function, by itself. A class method requires a class instance to be invoked, something along the lines of:

class Numerical_Integrator : public Generic Integrator{
    void integrate(SomeClass *instance, void (SomeClass::*f)() ){
         (instance->*f)();
    }
}

You need to revise the design of your templates, and/or class hierarchies in order to resolve this first. Once you correctly implement your class method invocation, implementing a template should not be an issue.



来源:https://stackoverflow.com/questions/37568257/c-passing-class-method-as-argument-to-a-class-method-with-templates

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!