如何将方法作为参数传递

How to pass a method as parameter?

本文关键字:参数传递 方法      更新时间:2023-10-16

拥有这个类:

class Automat
{
private:
    // some members ... 
public:
    Automat();
    ~Automat();
    void addQ(string& newQ) ; 
    void addCharacter(char& newChar)  ;
    void addLamda(Lamda& newLamda) ; 
    void setStartSituation(string& startQ) ; 
    void addAccQ(string& newQ) ;
    bool checkWord(string& wordToCheck) ; 
    friend istream& operator >> (istream &isInput, Automat &newAutomat);
    string& getSituation(string& startSituation) ; 
};

还有一个叫做Menu的类它有如下方法:

void Menu::handleStringSituations(string &stringOfSituation , Automat* autoToHandle ,void (Automat::*methodToDo) () )
{
    // some code ...
      (*autoToHandle).*methodToDo() ; 
}

(*autoToHandle).*methodToDo() ;行出现错误。

正如您所看到的,我试图将Automat类中的任何方法作为参数传递给handleStringSituations方法,但没有成功。

你怎么称呼它?c++不是一种动态类型语言;它是静态类型的。因此,您调用的所有内容都必须具有一组特定的参数,并且每个参数都必须键入。没有办法调用带有一定数量参数的"某个函数",并希望它能在运行时被排序。

你需要一个特定的接口。methodToDo需要有某种接口;没有它,你不能调用它。

最好的方法是使用多个版本的handleStringSituations,每个版本使用不同的成员指针类型:

void handleStringSituations(string &stringOfSituation , Automat* autoToHandle ,void (Automat::*methodToDo) ()) ;
void handleStringSituations(string &stringOfSituation , Automat* autoToHandle ,void (Automat::*methodToDo) (string&)) ;
void handleStringSituations(string &stringOfSituation , Automat* autoToHandle ,void (Automat::*methodToDo) (Lamda&)) ;

您尝试做的通常被称为闭包,这是函数式编程中的一个重要概念。与其重新发明轮子,我建议你看看Boost::Phoenix,它提供了一个不错的同行评审库。

http://www.boost.org/doc/libs/1_47_0/libs/phoenix/doc/html/index.html

然而,由于c++是一种静态类型语言,您将不得不做一些封送处理。c++中没有类似泛型函数(对象)的东西