我想定义一个函数的概念,该函数接受单个参数并返回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
}
这是一个演示。