C++ 使用C++;20 requires子句在常量表达式中不可用

C++ 使用C++;20 requires子句在常量表达式中不可用,c++,lambda,c++20,c++-concepts,C++,Lambda,C++20,C++ Concepts,在模板函数f中,我定义了一个带有模板参数列表的lambda,它可以使用if constexpr来检测类型U是否为std::vector: template <typename T> void f(T t) { auto g = []<typename U>(U u) { if constexpr (requires { std::same_as<U, std::vector<typename U::value_type>>; }) {

在模板函数
f
中,我定义了一个带有模板参数列表的lambda,它可以使用
if constexpr
来检测类型
U
是否为
std::vector

template <typename T>
void f(T t) {
  auto g = []<typename U>(U u) {
    if constexpr (requires { std::same_as<U, std::vector<typename U::value_type>>; }) {
      if constexpr (std::same_as<U, std::vector<typename U::value_type>>) {
        // deal with std::vector<U::value_type>
      }
    }
    else {
      // deal with other type
    }
  };
  g(t);
}

GCC出现内部编译器错误:

template <typename T>
void f(T t) {
  auto g = []<typename U>(U u) {
    if constexpr (requires { requires std::same_as<U, std::vector<typename U::value_type>>; }) {
      // deal with std::vector<U::value_type>
    }
    else {
      // deal with other type
    }
  };
  g(t);
}
<source>:19:23:   required from here
<source>:7:39: internal compiler error: in dependent_type_p, at cp/pt.c:26400
    7 |     if constexpr (requires { requires std::same_as<U, std::vector<typename U::value_type>>; }) {
      |                              ~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Please submit a full bug report,
with preprocessed source if appropriate.

它将正确编译。

这很可能是一个bug,这在新实现的功能中并不少见。我建议给他们的bug追踪器一次搜索,看看里面是否有类似的东西。我不确定这里发生了什么,但你使用的
相同。目前,该概念的真实性已被丢弃,因此您只需检查表达式的有效性(即
typename U::value_type
的有效性)。如果已知
typename U::value\U type
始终有效,则只要编写
If constexpr(std::same\U as)
(这将编译)。如果不是,则
如果constexpr(需要{requires std::same_as;})
(应该编译,但会导致GCC上的内部编译器错误)。即使在使用GCC的libstdc++时,这三个例子都是用叮当声编译的。你怎么能把U::value_类型与U::value_类型相同呢?@HolyBlackCat你是对的,我把
相同的_搞砸了。如果我理解正确,正确的约束应该是
需要{typename U::value\U type;需要std::same\U as;}
?我认为您不需要单独检查
typename U::value\U type。如果编译器在检查
std::same_as
时发现它无效,则整个
requires{…}
将自动返回false。
template <typename T>
void f(T t) {
  auto g = []<typename U>(U u) {
    if constexpr (requires { requires std::same_as<U, std::vector<typename U::value_type>>; }) {
      // deal with std::vector<U::value_type>
    }
    else {
      // deal with other type
    }
  };
  g(t);
}
<source>:19:23:   required from here
<source>:7:39: internal compiler error: in dependent_type_p, at cp/pt.c:26400
    7 |     if constexpr (requires { requires std::same_as<U, std::vector<typename U::value_type>>; }) {
      |                              ~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Please submit a full bug report,
with preprocessed source if appropriate.
void f(std::vector<int> t) {
  auto g = []<typename U>(U u) {
    if constexpr (requires { requires std::same_as<U, std::vector<typename U::value_type>>; }) {
      // deal with std::vector<U::value_type>
    }
    else {
      // deal with other type
    }
  };
  g(t);
}