Arn*_*ler 4 c++ predicate c++20
我试图限制 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;};
}
Run Code Online (Sandbox Code Playgroud)
你不能拥有一个接受“可以调用的东西”的函数。它必须是“可以使用一些已知(在声明时)类型的参数集来调用的东西”。这就是为什么std::predicate除了潜在的可调用类型之外还需要一组参数。
您的第一个示例之所以有效,是因为您没有为谓词概念提供任何参数,并且您的函数也没有采用任何参数。因此空参数列表与空参数列表匹配。
| 归档时间: |
|
| 查看次数: |
1133 次 |
| 最近记录: |