Reputation:
I want to define a concept of a function that takes in a single argument and returns bool
. Here is what I came up with:
template <typename T>
concept ConditionFunc = requires(T t) {
{ ConditionFunc(t) } -> std::same_as<bool>;
};
I want to use it like this
#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);
}
But I am getting an error because the concept requirements are not met. GCC reports that template type T
that is used to define the concept ConditionFunc
is deduced to be bool (*)(int)
but I expected it to be int
.
How can I define this concept correctly?
Upvotes: 2
Views: 371
Reputation: 60228
Your concept should be based on 2 types, the argument type T
, and the function type:
template <typename Func, typename T>
concept ConditionFunc = requires(T t, Func f) {
{ f(t) } -> std::same_as<bool>;
};
Then you can constrain Foo
to accept a function with the signature bool(T);
, like this:
template <typename T>
void Foo(std::vector<T>& v, ConditionFunc<T> auto &func)
{
// stuff
}
Here's a demo.
Upvotes: 2