【问题标题】:How can a clang 10 C++20 concept specify compound requirements for class methods?clang 10 C++20 概念如何为类方法指定复合要求?
【发布时间】:2020-12-27 11:23:24
【问题描述】:

我有一些代码试图使用一个概念来指定对类的成员函数的要求:

#include <type_traits>

template <typename A>
concept MyConcept = requires(A a, bool b) {
  { a.one() } -> bool;
  a.two();
  a.three(b);
};   

不幸的是,clang 10.0.0 在https://godbolt.org 上使用-std=c++20 会产生错误:

<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
};

任何帮助表示赞赏。

【问题讨论】:

  • 似乎它需要右侧的元函数:{ a.one() } -&gt; std::same_as&lt;bool&gt;;。正如例子所说。 :-)
  • 是的,前段时间提案中的语法已更改。
  • 当我使用带有 -std=c++20 的 x86-64 clang 10.0.0 在 Godbolt 上运行示例时,使用元函数的示例也给了我expected concept name with optional arguments 错误。

标签: c++ templates c++20 c++-concepts


【解决方案1】:

概念提案已更改,现在需要使用std::same_as

使用 Clang 10 可以很好地编译(尽管如果您没有标准库,您可能需要自己提供 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());
}

【讨论】:

  • 我已经尝试过 std::same_as 但在我的配置和 Godbolt 上,我继续看到“带有可选参数的预期概念名称”错误。
  • 这里是我所看到的链接:godbolt
  • 正如答案所说,您需要自己提供std::same_as,因为您的标准库不包含它。参见例如 cppreference 或 stackoverflow.com/questions/58509147/… 一个
  • 我明白了.. 感谢您的帮助。这里根据您引用的案例更新了godbolt,使用自定义的 same_as 实现 - 希望它充分包含歧义:)。
  • 不客气!希望在几周/几个月内,我们将拥有由 libstdc++ 和 libc++ 实现和发布的概念库,并且会更容易:-)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-24
  • 1970-01-01
  • 2020-09-24
  • 2021-11-27
相关资源
最近更新 更多