无法创建需要 bool 成员函数的 C++20 概念
Can't make C++20 concept requiring bool member function
此 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
必须 return 一个 可转换为 的类型 bool
.
这意味着您还可以指定 return 应该 恰好 一个 bool
,如果这是您想要的:
template <typename T>
concept testable = requires(T t)
{
{ t.foo() } -> std::same_as<bool>;
};
此 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
必须 return 一个 可转换为 的类型 bool
.
这意味着您还可以指定 return 应该 恰好 一个 bool
,如果这是您想要的:
template <typename T>
concept testable = requires(T t)
{
{ t.foo() } -> std::same_as<bool>;
};