Search code examples
c++cparametersoperator-keyword

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?


Solution

  • 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>());