我想有一个计算2个布尔变量的函数(如真值表)
例如:
因为
T | F:T
然后
myfunc('t', 'f', ||); /*defined as: bool myfunc(char lv, char rv, ????)*/
应该返回true;
如何传递第三个参数?(我知道可以将其作为char *传递,但随后我将不得不拥有另一个表来比较运算符字符串,然后执行我想避免的操作)
是否可以在函数/方法中传递类似^(XOR)或||(OR)或&&(AND)等运算符?
提前感谢
声明:
template<class Func> bool myfunc(char lv, char rv, Func func);
或如果您需要单独链接:
bool myfunc(char lv, char rv, std::function<bool(bool,bool)> func);
然后您可以致电:
myfunc('t', 'f', std::logical_or<bool>());
@@ ybungalobill发布了C ++正确答案,您应该坚持这样做。如果要传递运算符,则功能将不起作用,但是宏会起作用:
#define MYFUNC(lv, rv, op) ....
// Call it like this
MYFUNC('t', 'f', ||);
请注意,macros are evil。
您可以做的是定义返回特定类型的代理运算符。
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运算符是按位的,而不是逻辑的,尽管实际上差别不大。
但是,由于Lambda在C ++ 0x中存在,这是因为这种东西在C ++ 03中很烂。
很难实现。在C ++中,函数参数需要一个内存地址来找到其对象,而运算符则在编译时决定。运算符不会是对象。因此,您可以考虑使用MACRO完成您的任务。