Passing operator as a parameter

nacho4d picture nacho4d · Dec 25, 2010 · Viewed 19.1k times · Source

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 in a function/method?

Thanks in advance

Answer

Yakov Galka picture Yakov Galka · Dec 25, 2010

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