Passing operator as a parameter

帅比萌擦擦* 提交于 2019-12-03 10:45:20

问题


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


回答1:


Define:

bool myfunc(char lv, char rv, boost::function<bool(bool,bool)> func);

if you have boost, or

bool myfunc(char lv, char rv, std::function<bool(bool,bool)> func);

if you have C++0x compiler, or

template<class Func> bool myfunc(char lv, char rv, Func func);

If you want it to be a template. Then you can call:

myfunc('t', 'f', std::logical_or<bool>());



回答2:


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




回答3:


What you can do is define proxy operators that return specific types.

namespace detail {
    class or {
        bool operator()(bool a, bool b) {
            return a || b;
        }
    };
    class and {
        bool operator()(bool a, bool b) {
            return a && b;
        }
    };
    // etc
    class X {
        or operator||(X x) const { return or(); }
        and operator&&(X x) const { return and(); }
    };
};
const detail::X boolean;
template<typename T> bool myfunc(bool a, bool b, T t) {
     return t(a, b);
}
// and/or
bool myfunc(bool a, bool b, std::function<bool (bool, bool)> func) {
    return func(a, b);
}
// example
bool result = myfunc(a, b, boolean || boolean);

You can if desperate chain this effect using templates to pass complex logical expressions.

Also, the XOR operator is bitwise, not logical- although the difference is realistically nothing.

However, there's a reason that lambdas exist in C++0x and it's because this kind of thing flat out sucks in C++03.




回答4:


It's hard to be realized. In C++, function parameter need an memroy address to find its object, but operator is decided in compile time. Operator won't be a object. So you can think about MACRO to finish your task.



来源:https://stackoverflow.com/questions/4530588/passing-operator-as-a-parameter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!