【问题标题】:c++ passing class method as argument to a class method with templatesc ++将类方法作为参数传递给带有模板的类方法
【发布时间】:2016-09-30 19:08:39
【问题描述】:

我正在尝试使用模板将一个类方法传递给另一个类方法,但找不到任何关于如何做的答案(没有 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};
}

【问题讨论】:

  • Boost functionBoost bind?或者看看standard algorithm library 看看他们如何处理“谓词”?
  • 你需要 T 做什么?验证?
  • f(a, arg);this 的对象。
  • @thorsan:我希望能够为集成()提供任何东西。 @ coyotte508:好的,但是编译器即使不调用 f() 也会报错,请参见第一个示例中的注释行。

标签: c++ templates c++03 member-functions


【解决方案1】:

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

您的问题实际上是关于正确调用类方法。

以下非模板等效项也不起作用:

class SomeClass {

public:

     void method();
};

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

类方法不是函数,它本身不能作为函数调用。类方法需要调用类实例,类似于:

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

为了首先解决这个问题,您需要修改模板和/或类层次结构的设计。正确实现类方法调用后,实现模板应该不是问题。

【讨论】:

  • 感谢您的回答。但是使用 void integration(SomeClass instance, void (SomeClass::*f)() ) 仍然给出相同的错误:参数 2 从 '' 到 'void (Behavior:: )()'
  • 获取方法指针的正确语法是&amp;Class::method
  • 太棒了,现在可以编译了。我在哪里可以找到有关此的解释?谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-28
  • 2021-02-05
  • 1970-01-01
  • 2015-12-26
  • 2015-10-01
  • 1970-01-01
相关资源
最近更新 更多