Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing operator as a parameter

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?

like image 389
nacho4d Avatar asked Dec 25 '10 15:12

nacho4d


People also ask

Can we pass operator as argument?

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.

How do you pass a function as a parameter?

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.

How do you pass the operator as parameter in Kotlin?

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

Can you pass a function as a parameter C++?

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.


2 Answers

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>()); 
like image 160
Yakov Galka Avatar answered Sep 24 '22 12:09

Yakov Galka


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

like image 36
Karel Petranek Avatar answered Sep 21 '22 12:09

Karel Petranek