【发布时间】:2018-11-02 19:45:54
【问题描述】:
我正在寻找一种在两个谓词函数之间创建二元运算的方法。这是我的谓词函数声明:
template <typename T>
using Predicate = std::function<bool(T const&)>;
我正在寻找一种将两个谓词函数“合并”为一个的方法:
template <typename T>
static Predicate<T> andPredicate(Predicate<T> a, Predicate<T> b) {
// ???
}
预期行为:
Predicate<int> a = [](int a) { return a < 5; };
Predicate<int> b = [](int a) { return a > 0; };
Predicate<int> c = andPredicate(a, b); // a < 5 && a > 0
int number = 3;
bool result = c(number);
这样的事情在 C++ 中是否可行?
【问题讨论】:
-
为什么是静态的?
-
您需要返回一个 functionoid,当被调用时,它本身会使用自己的参数调用
a和b(它之前已存储)并返回其结果的and。你不远;)
标签: c++ functional-programming predicate