How to pass a method as parameter?

丶灬走出姿态 提交于 2019-12-30 03:19:13

问题


Having this class :

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

And also class called Menu which has the follow method :

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

The line (*autoToHandle).*methodToDo() ; gives an error .

As you can see I trying to pass any method from Automat class as a parameter to handleStringSituations method with no success.


回答1:


What you try to do is usually known as closure, a concept strong in functional programming. Rather than reinventing the wheel, I suggest you look into Boost::Phoenix, which provides this in a nice, peer reviewed library.

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

However, since C++ is a statically typed language, you will have to do some marshalling. There is no such thing like a generic function (object) in C++.




回答2:


How would you call it? C++ is not a dynamically typed language; it is statically typed. Therefore, everything you call must have a specific set of parameters, and each parameter must be typed. There's no way to call "some function" with some number of parameters and hope that it can be sorted out at runtime.

You need a specific interface. methodToDo needs to have some kind of interface; without one, you cannot call it.

The best you might be able to do is to have multiple versions of handleStringSituations, where each one takes a different member pointer type:

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&)) ;


来源:https://stackoverflow.com/questions/6852462/how-to-pass-a-method-as-parameter

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!