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

Passing an inherited method to another method

本文关键字:方法 另一个 继承      更新时间:2023-10-16

我正在尝试构建一个类,该类具有一个以方法为参数的成员函数。方法是在继承的类中定义的。我构建了一个最小的例子:

#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"
}

函数number中的当前语法适用于通用函数,但我无法使它适用于任何继承类的方法。

这里的问题是,您正在传递一个指向成员函数的指针,这与指向非成员函数的指针完全不同(number函数将其作为参数)。

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

int number(std::function<int(int)> f)
{
    return f(1);
}
...
number(std::bind(&option1::timesTwo, this, _1));

您还可以使用模板和额外的参数,如

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

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

static int timesTwo(int i){return 2*i;}

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

number([](int x){ return x * 2; });

给定的错误显示:

错误:必须调用对非静态成员函数的引用

您可以在方法成员之前添加static

我建议您使用std::function而不是指针函数。

工作代码:

#include <iostream>
#include <functional>
struct base
{
    base() {}
    int number(std::function<int(int)> f)
    {
        return f(1);
    }
};
struct option1 : base 
{
    static int timesTwo(int i){return 2*i;}
    option1() 
    {
        std::cout << number(timesTwo);
    }
};
struct option2 : base
{
    static int timesThree(int i){return 3*i;}
    static int timesFour (int i){return 4*i;}
    option2() 
    {
        std::cout << number(timesThree); 
    }
};
int main()
{
    option1 a; // now it works
}
相关文章: