gpt4 book ai didi

c++ - 为什么 GCC 在 std::tuple_size::value 的约束上成功,但在 std::tuple_size_v 的约束上失败?

转载 作者:行者123 更新时间:2023-12-02 18:39:54 28 4
gpt4 key购买 nike

在下面的代码中,为什么第二个和第三个概念会产生编译错误?

#include <tuple>

template <class P>
concept IsPair1 = std::tuple_size<P>::value == 2;

template <class P>
concept IsPair2 = std::tuple_size_v<P> == 2;

template <class P>
concept IsPair3 = requires { typename std::tuple_size<P>; } && std::tuple_size_v<P> == 2;

constexpr bool intIsPair1 = IsPair1<int>; // OK, false

constexpr bool intIsPair2 = IsPair2<int>; // error: incomplete type 'std::tuple_size<int>' used in nested name specifier

constexpr bool intIsPair3 = IsPair3<int>; // error: incomplete type 'std::tuple_size<int>' used in nested name specifier
/usr/local/Cellar/gcc/11.1.0_1/include/c++/11.1.0/tuple:1334:61: error: incomplete type 'std::tuple_size<int>' used in nested name specifier
1334 | inline constexpr size_t tuple_size_v = tuple_size<_Tp>::value;
| ^~~~~

根据 https://en.cppreference.com/w/cpp/language/constraints,我希望所有三个都被评估为 false ,

Satisfaction of an atomic constraint is checked by substituting the parameter mapping and template arguments into the expression E. If the substitution results in an invalid type or expression, the constraint is not satisfied.

最佳答案

变量模板的初始值设定项不在 immediate context 中,因此那里的任何错误都会导致硬错误而不是替换失败。

std::tuple_size<P>::value == 2之所以有效,是因为尝试命名成员 value不完整类型在直接上下文中。

requires { typename std::tuple_size<P>; } && std::tuple_size_v<P> == 2不起作用,因为第一部分只检查 std::tuple_size<P>是一种类型,自 tuple_size 以来很容易满足是一个不受约束的类模板。

关于c++ - 为什么 GCC 在 std::tuple_size::value 的约束上成功,但在 std::tuple_size_v 的约束上失败?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68143642/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com