I want to have a function that evaluates 2 bool
vars (like a truth table).
For example:
Since
T | F : T
then
myfunc('t', 'f', ||); /*defined as: bool myfunc(char lv, char rv, ????)*/
should return true;
.
How can I pass the third parameter?
(I know is possible to pass it as a char* but then I will have to have another table to compare operator string and then do the operation which is something I would like to avoid)
Is it possible to pass an operator like ^
(XOR) or ||
(OR) or &&
(AND), etc to a function/method?
I'd pass it as a string, then determine the passed string in the function and e.g use a switch construct to do the corresponding operation. Operators can't be passed like that, and they can't generally be substited by variables, so operators suck that way.
Function Call When calling a function with a function parameter, the value passed must be a pointer to a function. Use the function's name (without parentheses) for this: func(print); would call func , passing the print function to it.
(Int)->Int can be passed into a parameter expecting (Int, Int)->Int because the receiver this will be passed in as the first parameter. Interesting that the signature doesn't match, but because of the receiver being the first parameter it still works. cool.
Passing a function as parameter to another functionC++ has two ways to pass a function as a parameter. As you see, you can use either operation() or operation2() to give the same result.
Declare:
template<class Func> bool myfunc(char lv, char rv, Func func);
Or if you need to link it separately:
bool myfunc(char lv, char rv, std::function<bool(bool,bool)> func);
Then you can call:
myfunc('t', 'f', std::logical_or<bool>());
@ybungalobill posted a C++ correct answer and you should stick to it. If you want to pass the operators, functions will not work, but macros would do the work:
#define MYFUNC(lv, rv, op) .... // Call it like this MYFUNC('t', 'f', ||);
Be careful, macros are evil.
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