gpt4 book ai didi

c++ - 为什么 std::extent 应用于 auto& 会产生零?

转载 作者:可可西里 更新时间:2023-11-01 18:29:12 25 4
gpt4 key购买 nike

我正在试验 constexpr auto和字符串文字以获得我可以与 std::begin 一起使用的字符数组以一般方式,当我遇到无法解释的事情时:表达式 std::extent<decltype(foo)>::value , 其中foo使用自动引用声明,产生零。

 #include <iostream>
#include <type_traits>

namespace {
auto& ARRAY_REFERENCE = "foo";

template<typename T, std::size_t N>
std::size_t numberOfElementsIn(T (&)[N]) { return N; }
}

int main() {
std::cerr <<
"std::extent applied to ARRAY_REFERENCE: " << std::extent<decltype(ARRAY_REFERENCE)>::value << "\n"
"Number of elements in ARRAY_REFERENCE: " << numberOfElementsIn(ARRAY_REFERENCE) << "\n"
;
return 0;
}

上面的代码给出了输出

std::extent applied to ARRAY_REFERENCE: 0
Number of elements in ARRAY_REFERENCE: 4

为什么不包含std::extent的表达式评估为 4?

最佳答案

对 RTFM 表示抱歉(不是抱歉),但来自 std::extent at cppreference.com :

If T is an array type, provides the member constant value equal to the number of elements along the Nth dimension of the array, if N is in [0, std::rank<T>::value). For any other type, or if T is array of unknown bound along its first dimension and N is 0, value is 0.

你的 T不是数组类型;它是一个引用类型。

您可以使用 std::remove_reference 解决此问题:

std::extent<std::remove_reference<decltype(ARRAY_REFERENCE)>::type>::value

( live demo )

C++ 不是很棒吗?

关于c++ - 为什么 std::extent 应用于 auto& 会产生零?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36333965/

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