gpt4 book ai didi

c++ - 如何定义返回 bool 值的函数的概念

转载 作者:行者123 更新时间:2023-12-01 14:42:41 25 4
gpt4 key购买 nike

我想定义一个函数的概念,该函数接受单个参数并返回bool。这是我想出的:

template <typename T>
concept ConditionFunc = requires(T t) {
{ ConditionFunc(t) } -> std::same_as<bool>;
};

我想这样使用
#include <concepts>
#include <vector>

bool IsEven(int n)
{
return n % 2 == 0;
}

template <typename T>
void Foo(std::vector<T>& v, ConditionFunc auto func)
{
// stuff
}

int main()
{
std::vector<int> vec = {1, 2, 3, 4, 5};
Foo(v, IsEven);
}

但是由于没有满足概念要求,我遇到了错误。 GCC报告说,用于定义概念 T的模板类型 ConditionFunc被推导为 bool (*)(int),但我希望它是 int

如何正确定义这个概念?

最佳答案

您的概念应基于两种类型,参数类型T和函数类型:

template <typename Func, typename T>
concept ConditionFunc = requires(T t, Func f) {
{ f(t) } -> std::same_as<bool>;
};

然后,您可以约束 Foo接受带有签名 bool(T);的函数,如下所示:
template <typename T>
void Foo(std::vector<T>& v, ConditionFunc<T> auto &func)
{
// stuff
}

这是 demo

关于c++ - 如何定义返回 bool 值的函数的概念,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62325094/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com