如何定义 returns bool 函数的概念
How to define concept of a function that returns bool
我想定义一个接受单个参数和 returns 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 报告用于定义概念 ConditionFunc
的模板类型 T
被推断为 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。
我想定义一个接受单个参数和 returns 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 报告用于定义概念 ConditionFunc
的模板类型 T
被推断为 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。