【问题标题】:Type requirement in C++ concepts (C++20)C++ 概念中的类型要求 (C++20)
【发布时间】:2020-06-02 22:21:12
【问题描述】:

我正在使用 g++ 10 学习新实现的 C++20 标准概念。 我坚持一个简单的类型要求。即我想实现模板参数T 具有T::inner 成员名称的要求。 这是我的错误代码。这个简单的代码有什么问题以及如何修复它?

#include<concepts>

template<typename T>
concept ContainsInner = requires
{
  typename T::inner;
};

template<ContainsInner T>
struct S{};

struct Q
{
  int inner;
};

int main()
{
  S<Q> s;     // instantiate S with Q for template type, 
              // which must satisfy the ContainsInner concept.
              // Q indeed contains the inner name but still the compilation fails
}

【问题讨论】:

  • 为什么投反对票?

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


【解决方案1】:

这个:

template<typename T>
concept ContainsInner = requires
{
  typename T::inner;
};

要求T 有一个名为inner类型。哪个 gcc 在它的错误中告诉你:

source>:6:12: note: the required type 'typename T::inner' is invalid
    6 |   typename T::inner;
      |   ~~~~~~~~~^~~~~~~~~

Q 没有名为inner类型。如果您想要一个名为inner 的成员变量,那么您想要:

template<typename T>
concept ContainsInner = requires(T t) {
    t.inner;
};

请注意,这甚至不检查它是什么类型,只是检查它是否存在。这不是很有用。也许您想要求它是int

template<typename T>
concept ContainsInner = requires(T t) {
    { t.inner } -> std::same_as<int&>;
};

【讨论】:

  • 谢谢,您的回答很透彻并澄清了问题。
  • 关于你的代码行{ t.inner } -&gt; std::same_as&lt;int&amp;&gt;的两个问题。 same_as concept 根据 cppreference.com 需要 2 个参数,但您只使用一个。尽管如此,它仍然有效,但为什么呢?为什么是int&amp; 而不是int
  • @IgorPopov:如果您将两个模板参数都提供给std::same_as,它将如何处理被检查的表达式类型?它是int&amp;,因为它是一个左值(从表达式的形式来看是必需的,但仍然必须是你的表达方式)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-12
  • 1970-01-01
  • 2021-10-06
  • 2020-12-27
  • 2021-11-27
  • 2020-09-28
相关资源
最近更新 更多