我有一些代码尝试使用一种概念来指定类的成员函数的要求:
#include <type_traits>
template <typename A>
concept MyConcept = requires(A a, bool b) {
{ a.one() } -> bool;
a.two();
a.three(b);
};
不幸的是,在https://godbolt.org上使用-std=c++20
的clang 10.0.0产生错误:<source>:5:18: error: expected concept name with optional arguments [clang-diagnostic-error]
{ a.one() } -> bool;
^
有没有人对clang期望的语法有了解?我已经根据来自各种来源(例如Compound Requirements sample)的样本尝试了多种变体,但到目前为止还没有运气:#include <type_traits>
template<typename T> concept C2 =
requires(T x) {
{*x} -> std::convertible_to<typename T::inner>; // the expression *x must be valid
// AND the type T::inner must be valid
// AND the result of *x must be convertible to T::inner
{x + 1} -> std::same_as<int>; // the expression x + 1 must be valid
// AND std::same_as<decltype((x + 1)), int> must be satisfied
// i.e., (x + 1) must be a prvalue of type int
{x * 1} -> std::convertible_to<T>; // the expression x * 1 must be valid
// AND its result must be convertible to T
};
任何帮助表示赞赏。
最佳答案
概念提案已更改,现在需要使用std::same_as
。
使用Clang 10可以很好地进行编译(尽管如果没有stdlib,则可能需要自己提供std::same_as
):
template <typename A>
concept MyConcept = requires(A a, bool b) {
{ a.one() } -> std::same_as<bool>;
a.two();
a.three(b);
};
struct SomeType {
bool one() { return true; }
void two() {}
void three(bool) {}
};
bool foo(MyConcept auto a) {
return a.one();
}
void bar() {
foo(SomeType());
}
关于c++ - clang 10 C++ 20概念如何为类方法指定复合要求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63804666/