获取 std::array 的大小作为右值
Get the size of an std::array as r-value
考虑以下代码片段:
#include<array>
#include<cstdint>
const std::array<int, 3> array{0, 1 , 2};
template<class string_type>
auto parse(string_type&& name) {
const auto s = std::uint8_t{array.size()};
return s;
}
虽然它使用 gcc 9.3.0(Ubuntu 20.04 上的默认设置)进行编译,但使用 gcc 11.2.0(从源代码构建)失败并显示以下错误消息:
test2.cpp: In function ‘auto parse(string_type&&)’:
test2.cpp:8:47: error: no matching function for call to ‘std::array<int, 3>::size(const std::array<int, 3>*)’
8 | const auto s = std::uint8_t{array.size()};
| ~~~~~~~~~~^~
In file included from test2.cpp:1:
/opt/modules/install/gcc/11.2.0/include/c++/11.2.0/array:176:7: note: candidate: ‘constexpr std::array<_Tp, _Nm>::size_type std::array<_Tp, _Nm>::size() const [with _Tp = int; long unsigned int _Nm = 3; std::array<_Tp, _Nm>::size_type = long unsigned int]’
176 | size() const noexcept { return _Nm; }
| ^~~~
/opt/modules/install/gcc/11.2.0/include/c++/11.2.0/array:176:7: note: candidate expects 0 arguments, 1 provided
除了没有多大意义外,我找不到错误在哪里,你能帮我吗?
这似乎是一个错误:
- gcc-10:https://godbolt.org/z/95TTv4z9P 和
- gcc-11: https://godbolt.org/z/KWMs4MMcK
它适用于:
要变通,您可以执行以下任一操作:
const auto s = static_cast<std::uint8_t>(array.size());
或者这个:
const std::uint8_t s = array.size();
或这个(但请不要):
const auto s = std::uint8_t( array.size() );
我建议这样做:
#include<array>
#include<cstdint>
const std::array<int, 3> array{ 0, 1 , 2 };
template<class string_type>
auto parse(string_type&& name)
{
const std::uint8_t s = array.size();
return s;
}
考虑以下代码片段:
#include<array>
#include<cstdint>
const std::array<int, 3> array{0, 1 , 2};
template<class string_type>
auto parse(string_type&& name) {
const auto s = std::uint8_t{array.size()};
return s;
}
虽然它使用 gcc 9.3.0(Ubuntu 20.04 上的默认设置)进行编译,但使用 gcc 11.2.0(从源代码构建)失败并显示以下错误消息:
test2.cpp: In function ‘auto parse(string_type&&)’:
test2.cpp:8:47: error: no matching function for call to ‘std::array<int, 3>::size(const std::array<int, 3>*)’
8 | const auto s = std::uint8_t{array.size()};
| ~~~~~~~~~~^~
In file included from test2.cpp:1:
/opt/modules/install/gcc/11.2.0/include/c++/11.2.0/array:176:7: note: candidate: ‘constexpr std::array<_Tp, _Nm>::size_type std::array<_Tp, _Nm>::size() const [with _Tp = int; long unsigned int _Nm = 3; std::array<_Tp, _Nm>::size_type = long unsigned int]’
176 | size() const noexcept { return _Nm; }
| ^~~~
/opt/modules/install/gcc/11.2.0/include/c++/11.2.0/array:176:7: note: candidate expects 0 arguments, 1 provided
除了没有多大意义外,我找不到错误在哪里,你能帮我吗?
这似乎是一个错误:
- gcc-10:https://godbolt.org/z/95TTv4z9P 和
- gcc-11: https://godbolt.org/z/KWMs4MMcK
它适用于:
要变通,您可以执行以下任一操作:
const auto s = static_cast<std::uint8_t>(array.size());
或者这个:
const std::uint8_t s = array.size();
或这个(但请不要):
const auto s = std::uint8_t( array.size() );
我建议这样做:
#include<array>
#include<cstdint>
const std::array<int, 3> array{ 0, 1 , 2 };
template<class string_type>
auto parse(string_type&& name)
{
const std::uint8_t s = array.size();
return s;
}