和 c++ 中的两个谓词函数

and two predicate functions in c++

我正在寻找一种在两个谓词函数之间创建二元运算的方法。这是我的谓词函数声明:

template <typename T>
using Predicate = std::function<bool(T const&)>;

我正在寻找一种方法 'concat' 将两个谓词函数合二为一:

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++ 中可以实现这样的功能吗?

这应该有效:

template <typename T>
static Predicate<T> andPredicate(Predicate<T> a, Predicate<T> b) {
   return [a,b]( T const &val ) { return a( val ) and b( val ) };
}

不清楚为什么要将其设为静态。

当然,只需使用 lambda:

template <typename T>
Predicate<T> andPredicate(Predicate<T> a, Predicate<T> b) {
    return [=](T i) { return a(i) && b(i); };
}

您甚至可以通过利用模板避免 std::function 的额外开销:

template <typename P1, typename P2>
auto andPredicate(P1&& a, P2&& b) {
    return [a = std::forward<P1>(a), b = std::forward<P2>(b)](const auto& i) {
        return a(i) && b(i);
    };
}

Live Demo

这通过接受原始谓词所需的实际类型并直接返回 lambda,避免了 std::function 的额外类型擦除开销。如果需要,您可以将其存储在 std::function 中,或者让编译器使用 auto.

推断类型