问题
I have a simple code snippet below, which compiles using:
g++-9 -std=c++2a -fconcepts
This is trying to define a concept that requires the presence of a function. I would expect the output to be "yes" but it's not... Any idea why? Thanks.
#include <iostream>
template <typename T>
concept bool HasFunc1 =
requires(T) {
{ T::func1() } -> int;
};
struct Test
{
int func1()
{
return 5;
}
};
int main()
{
if constexpr (HasFunc1<Test>)
std::cout << "yes\n";
}
回答1:
You are testing for presence of a static member function. What you want is
template <typename T>
concept bool HasFunc1 =
requires(T t) {
{ t.func1() } -> int;
};
回答2:
Try calling it yourself:
Test::func1();
prog.cc: In function 'int main()':
prog.cc:19:14: error: cannot call member function 'int Test::func1()' without object
19 | Test::func1();
| ^
Oh, right. func1
should either be a static
member function, or you should call it on an instance inside your concept:
template <typename T>
concept bool HasFunc1 =
requires(T t) {
{ t.func1() } -> int;
};
来源:https://stackoverflow.com/questions/58394556/c-concepts-can-i-have-a-constraint-requiring-a-function-be-present-in-a-clas