将继承的方法传递给另一个方法

Rob*_*yen 2 c++ methods inheritance

我正在尝试使用方法作为参数构建一个具有成员函数的类.这些方法在继承的类中定义.我构建了一个最小的例子:

#include <iostream>

struct base
{
    base() {}

    int number(int (*f)(int))
    {
        return f(1);
    }
};

struct option1 : base 
{
    int timesTwo(int i){return 2*i;}
    option1() 
    {
        std::cout << number(timesTwo);
    }
};

struct option2 : base
{
    int timesThree(int i){return 3*i;}
    int timesFour (int i){return 4*i;}
    option2() 
    {
        std::cout << number(timesThree);
    }
};

int main()
{
    option1 a; //I would expect this to print "2"
}
Run Code Online (Sandbox Code Playgroud)

函数中的当前语法number是针对一般函数的,但我无法使其适用于任何继承类的方法.

Som*_*ude 5

这里的问题是你传递一个指向成员函数的指针,这与指向非成员函数的指针(这是你的number函数作为参数的指针)完全不同.

你可以使用std::functionstd::bind:

int number(std::function<int(int)> f)
{
    return f(1);
}

...

number(std::bind(&option1::timesTwo, this, _1));
Run Code Online (Sandbox Code Playgroud)

你也可以使用模板和额外的参数,比如

template<typename T>
int number(T* object, int(T::*f)(int))
{
    return (object->*f)(1);
}

...

number(this, &option1::timesTwo);
Run Code Online (Sandbox Code Playgroud)

或者简单(但并不总是正确,取决于情况和用例):制作回调函数static:

static int timesTwo(int i){return 2*i;}
Run Code Online (Sandbox Code Playgroud)

我的建议是你使用查看解决方案std::function,因为这样很容易number用任何类型的可调用对象调用函数,比如lambda:

number([](int x){ return x * 2; });
Run Code Online (Sandbox Code Playgroud)