[英]When and how should I use std::predicate
我试图约束 Callable 在评估时返回布尔值。 我一直在尝试使用概念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;};
}
你不能有一个接受“可以调用的东西”的函数。 它必须是“可以用一组已知(在声明时)类型的参数调用的东西”。 这就是为什么std::predicate
除了潜在的可调用类型之外还需要一组参数的原因。
您的第一个示例有效,因为您没有为谓词概念提供任何参数,并且您的函数也没有采用任何参数。 所以空参数列表匹配空参数列表。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.