关于概念和要求的使用问题

use*_*524 1 c++ c++20

有谁知道为什么下面这段代码返回0?什么时候会返回1?

#include <iostream>
#include <type_traits>

template<typename T>
concept A = requires(T t){{t} -> std::same_as<bool>;};
int main()
{
    std::cout << A<bool> << "\n";
}
Run Code Online (Sandbox Code Playgroud)

我使用 gcc13.1 (编译器选项:-std=c++20)在编译器资源管理器上运行它,它确实返回 0。

康桓瑋*_*康桓瑋 5

在您的情况下,复合要求{t} -> same_as<bool>意味着 的类型decltype((t))必须满足same_as<bool>

由于tindecltype((t))带括号,因此它将被视为普通的左值表达式,这使得它具有类型bool&而不是bool因此不满足约束。

您可以将返回类型限制为same_as<bool&>或使用 C++23衰减复制( auto(x)) 来删除表达式的cvref限定符

template<typename T>
concept A = requires(T t) {
  { auto(t) } -> std::same_as<bool>;
};
Run Code Online (Sandbox Code Playgroud)