为什么 std::extent 应用于 auto&的产量为零?
Why does std::extent applied to auto& yield zero?
我正在试验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?
对RTF感到抱歉(不抱歉),但来自cppreference.com:上的std::extent
如果
T
是数组类型,则如果N
在[0, std::rank<T>::value)
中,则提供等于沿数组的第N
维度的元素数量的成员常数value
对于任何其他类型,或者如果T
是沿其第一维度的未知边界的数组,并且N
为0,则value
为0。
您的T
不是数组类型;它是一个引用类型。
您可以使用std::remove_reference
:修复此问题
std::extent<std::remove_reference<decltype(ARRAY_REFERENCE)>::type>::value
(现场演示)
C++不是很棒吗?
相关文章:
- 使用std::multimap迭代器创建std::list
- C++中std::resize(n)和std::shrink_to_fit之间的区别
- 来自 std::list 的迭代器 .end() 按预期返回"0xcdcdcdcdcdcdcdcd"但 .begin()
- C++17复制构造函数,在std::unordereded_map上进行深度复制
- 如何导出包含具有"std::unique_ptr"值的"std::map"属性的
- 从持续时间构造std::chrono::system_clock::time_point
- std::具有相同基类的类的变体
- std::向量与传递值的动态数组
- 使用std::vector的OpenCL矩阵乘法
- std::map<struct,struct>::find 找不到匹配项,但是如果我循环通过 begin() 到 end(),我在那里看到匹配项
- std::condition_variable::wait()如何评估给定的谓词
- 如何获取std::result_of函数的返回类型
- std::原子加载和存储都需要吗
- 将对象移动到std::shared_ptr
- POCO::PostgreSQL:如何将std::vector支持添加到`Binder::bind`
- 使用一个考虑到std::map中键值的滚动或换行的键
- std::extent 实现详细信息说明
- 为什么数组与 std::extent 第二个 imp 匹配
- 为什么 std::extent 应用于 auto&的产量为零?
- 在std::数组上使用std::extent