简体   繁体   English

我应该何时以及如何使用 std::predicate

[英]When and how should I use std::predicate

I am trying to constrain a Callable to return a boolean when evaluated.我试图约束 Callable 在评估时返回布尔值。 I have been trying to use the concept std::predicate , but it does not seem to do what I want it to do.我一直在尝试使用概念std::predicate ,但它似乎没有做我想做的事。

So I defined my own concept, that is invokable and returns something convertible to a boolean.所以我定义了自己的概念,即可调用并返回可转换为布尔值的东西。 But again, I struggle understanding what I can or can not do with it, and I wonder what are the actual use cases of std::predicate ?但同样,我很难理解我能用它做什么或不能做什么,我想知道std::predicate的实际用例是什么?

#include<concepts>
#include<string>

template<class F, class... Args>
concept Predicate = std::invocable<F, Args...> &&
                    std::convertible_to<std::invoke_result_t<F, Args...>, bool>;

int main(int argc, char *argv[])
{ 
 constexpr Predicate auto f1 = [](){return true;}; // ok
 constexpr std::predicate auto f2 = [](){return true;}; // ok
 constexpr int x = 34;
 constexpr Predicate auto f3 = [x](){ return x==42;}; // ok

 // Pas ok:  error: deduced initializer does not satisfy placeholder constraints
 //constexpr Predicate auto f4 = [](auto x){ return x==42;}; 
 //constexpr std::predicate auto f5 = [](auto x){ return x==42;};
}

You cannot have a function that takes a "thing that can be called".你不能有一个接受“可以调用的东西”的函数。 It must be a "thing that can be called with some set of arguments of known (at the time of the declaration) types".它必须是“可以用一组已知(在声明时)类型的参数调用的东西”。 That's why std::predicate takes a set of arguments in addition to the potential callable type.这就是为什么std::predicate除了潜在的可调用类型之外还需要一组参数的原因。

Your first examples work because you didn't give the predicate concept any arguments and your functions also didn't take any parameters.您的第一个示例有效,因为您没有为谓词概念提供任何参数,并且您的函数也没有采用任何参数。 So an empty argument list matches the empty parameter list.所以空参数列表匹配空参数列表。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM