将运算符作为参数传递

时间:2010-12-25 15:06:44

标签: c++ c parameters operator-keyword

我想要一个评估2个bool变量的函数(如真值表)

例如:

T | F:T

然后

myfunc('t', 'f', ||);  /*defined as: bool myfunc(char lv, char rv, ????)*/

应该返回true;

我怎样才能传递第三个参数? (我知道可以将它作为char *传递但是我必须有另一个表来比较运算符字符串,然后执行我想避免的操作)

是否可以在函数/方法中传递^(XOR)或||(OR)或&&(AND)等运算符?

提前致谢

5 个答案:

答案 0 :(得分:26)

定义:

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

如果你有提升,或

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

如果您有C ++ 0x编译器,或

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

如果您希望它成为模板。然后你可以打电话:

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

答案 1 :(得分:5)

@ybungalobill发布了一个C ++正确答案,你应该坚持下去。如果你想传递运算符,函数将不起作用,但宏将完成工作:

#define MYFUNC(lv, rv, op) ....

// Call it like this
MYFUNC('t', 'f', ||);

小心,macros are evil

答案 2 :(得分:2)

您可以做的是定义返回特定类型的代理运算符。

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

如果使用模板绝望地将此效果链接起来以传递复杂的逻辑表达式,则可以。

此外,XOR运算符是按位的,不是逻辑运算符 - 尽管差别实际上没有。

然而,有一个原因是在C ++ 0x中存在lambdas,这是因为这种事情在C ++ 03中很糟糕。

答案 3 :(得分:0)

在现代 C++ 中,可以使用 lambda 传递任何运算符。
更新 1:提议的解决方案引入了@HolyBlackCat 建议的小改进

#include <iostream>

template<class T, class F> void reveal_or(T a, T b, F f)
{
    // using as function(a, b) instead of expression a || b is the same thing
    if ( f(a, b) ) 
        std::cout << a << " is || " << b << std::endl;
    else
        std::cout << a << " is not || " << b << std::endl;

}

template<class T> void reveal_or(T a, T b)
{
    // reuse the already defined ||
    reveal_or(a, b, [](T t1, T t2) {return t1 || t2; });
}

如果 || 不用理会如何传递参数运算符已定义

int main ()
{
    reveal_or('1', 'a');
    return 0;
}

作为参数显式传递。我们可以传递任何东西,包括任何异国情调的废话

int main ()
{
    //same as above:
    reveal_or('1', 'a', [](char t1, char t2) { return t1 || t2; });
    //opposite of above
    reveal_or('1', 'a', [](char t1, char t2) { return !( t1 || t2; ) });

    return 0;
}

答案 4 :(得分:-1)

很难实现。在C ++中,函数参数需要一个memroy地址来查找它的对象,但是运算符是在编译时确定的。操作员不是对象。所以你可以考虑MACRO来完成你的任务。

相关问题