C++:将类方法作为参数传递给具有模板的类方法

3

我正在尝试使用模板将一个类方法传递给另一个类方法,但是找不到任何关于如何实现的答案(不能使用C++11,可以使用boost):

我将核心问题简化为以下内容:

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

2
Boost函数和Boost绑定?或者看一下标准算法库,并查看它们如何处理“谓词”? - Some programmer dude
你需要 T 是用来做什么的?验证吗? - thorsan
f(a, arg);<- 你还需要将作为函数 this 的对象传入。 - coyotte508
@thorsan:我想能够将任何东西传递给integrate()函数。 @coyotte508:好的,但是即使不调用f()函数,编译器也会抱怨,可以看到第一个示例中的注释行。 - Napseis
1个回答

8

你的问题并不是关于将类方法作为模板参数传递。

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

下面这个非模板等价物也无法工作:

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 integrate(SomeClass *instance, void (SomeClass::f)() )仍然会出现相同的错误:从“<未解决的重载函数类型>”到“void(Behavior ::)()”没有已知的转换。 - Napseis
1
获取方法指针的正确语法是 &Class::method - Sam Varshavchik
太棒了,现在它可以编译了。我在哪里可以找到关于这个的解释?谢谢。 - Napseis

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接