How to pass a method as parameter?

后端 未结 2 1109
南笙
南笙 2020-12-31 22:32

Having this class :

class Automat
{
private:
    // some members ... 
public:
    Automat();
    ~Automat();
    void addQ(string& newQ) ; 
    void addC         


        
相关标签:
2条回答
  • 2020-12-31 22:46

    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++.

    0 讨论(0)
  • 2020-12-31 22:47

    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&)) ;
    
    0 讨论(0)
提交回复
热议问题