这个MCVE在Visual Studio(2019,C++20标志打开)和G++10(同样,C++20选项设置)中都遇到了麻烦。 每种情况下的抱怨都是bool
不是类型约束。 (那么,我应该键入什么来要求给定类型具有这样的成员函数呢?)
#include <concepts>
template <typename T>
concept testable = requires(T t)
{
{ t.foo() } -> bool; //Error is here: "expected a concept" or
// "return-type-requirement is not a type-constraint"
};
class A
{
public:
bool foo() const { return true; }
};
template<testable T>
void verify(const T& t) { assert(t.foo()); }
int main(void)
{
A a; verify(a);
return 0;
}
这个概念需要写成:
template <typename T>
concept testable = requires(T t)
{
{ t.foo() } -> std::convertible_to<bool>;
};
请注意,这实际上在foo
的约束中更为明确。 它说,调用foo
必须返回可转换为bool
的类型。
这意味着您还可以指定返回值应该是一个bool
,如果您想这样做的话:
template <typename T>
concept testable = requires(T t)
{
{ t.foo() } -> std::same_as<bool>;
};