c ++将类方法作为参数传递给带有模板的类方法 [英] c++ passing class method as argument to a class method with templates

查看:41
本文介绍了c ++将类方法作为参数传递给带有模板的类方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用模板将一个类方法传递给另一个类方法,但找不到关于如何做的任何答案(没有 C++11,boost ok):

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):

我将核心问题简化为:

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};
}

我收到错误:

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::*)()’

谢谢.

奖励:关于参数呢?

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};
}

推荐答案

您的问题实际上并不是关于将类方法作为模板参数的一部分进行传递.

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.

这篇关于c ++将类方法作为参数传递给带有模板的类方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆