我正在试验 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 constantvalue
equal to the number of elements along theN
th dimension of the array, ifN
is in[0, std::rank<T>::value)
. For any other type, or ifT
is array of unknown bound along its first dimension andN
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/