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.
Pass a Method as a Parameter by Using the lambda Function in Java. This is a simple example of lambda, where we are using it to iterate the ArrayList elements. Notice that we're passing the lambda function to the forEach() method of the Iterable interface. The ArrayList class implements the Iterable interface.
Yes it is, just use the name of the method, as you have written. Methods and functions are objects in Python, just like anything else, and you can pass them around the way you do variables. In fact, you can think about a method (or function) as a variable whose value is the actual callable code object.
We can't directly pass the whole method as an argument to another method. Instead, we can call the method from the argument of another method. // pass method2 as argument to method1 public void method1(method2()); Here, the returned value from method2() is assigned as an argument to method1() .
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&)) ;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With