C++ 概念中的类型要求 (C++20)

Type requirement in C++ concepts (C++20)

我正在使用 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
}

这个:

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 没有名为 innertype。如果你想要的是有一个名为 inner 的成员 variable,那么你想要:

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