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

标签 c++ c++11

我正在试验 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/

相关文章:

datetime - 处理亚秒精度 UTC 时间算术中的闰秒

c++ - 在 C++ 中抛出运行时警告

c++ - 库达错误 : unexpected launch failure

c++ - 在 opencv 中创建 4x4 mat 矩阵时出错

c++ - 具有没有任何构造函数的标准布局结构的 RVO

c++ - 在哪里可以了解有关 C++0x 的更多信息?

c++ - 在 C++ 中是否有等效的 Java equals 方法?

c++ - MIDL。为什么回调 C++ 接口(interface)在方法添加到 idl 后不更新?

c++ - 使用默认关键字时的 Visual Studio C2580

c++ - 静态转换如何在 C++ 中保持数字的精度?