Passing operator as a parameter

后端 未结 4 1558
我在风中等你
我在风中等你 2021-02-05 03:25

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         


        
4条回答
  •  暖寄归人
    2021-02-05 03:48

    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 bool myfunc(bool a, bool b, T t) {
         return t(a, b);
    }
    // and/or
    bool myfunc(bool a, bool b, std::function 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.

提交回复
热议问题