获取 std::array 的大小作为右值

a_r*_*ser 7 c++ c++17

考虑以下代码片段:

\n
#include<array>\n#include<cstdint>\n\nconst std::array<int, 3> array{0, 1 , 2};\n\ntemplate<class string_type>\nauto parse(string_type&& name) {\n        const auto s = std::uint8_t{array.size()};\n        return s;\n}\n
Run Code Online (Sandbox Code Playgroud)\n

虽然它使用 gcc 9.3.0(Ubuntu 20.04 上的默认值)进行编译,但使用 gcc 11.2.0(从源代码构建)会失败,并显示以下错误消息:

\n
test2.cpp: In function \xe2\x80\x98auto parse(string_type&&)\xe2\x80\x99:\ntest2.cpp:8:47: error: no matching function for call to \xe2\x80\x98std::array<int, 3>::size(const std::array<int, 3>*)\xe2\x80\x99\n    8 |         const auto s = std::uint8_t{array.size()};\n      |                                     ~~~~~~~~~~^~\nIn file included from test2.cpp:1:\n/opt/modules/install/gcc/11.2.0/include/c++/11.2.0/array:176:7: note: candidate: \xe2\x80\x98constexpr 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]\xe2\x80\x99\n  176 |       size() const noexcept { return _Nm; }\n      |       ^~~~\n/opt/modules/install/gcc/11.2.0/include/c++/11.2.0/array:176:7: note:   candidate expects 0 arguments, 1 provided\n
Run Code Online (Sandbox Code Playgroud)\n

运行示例

\n

除了它没有多大意义之外,我找不到错误在哪里,你能帮助我吗?

\n

Inn*_*der 2

这似乎是一个错误:

它在以下情况下运行良好:

要解决此问题,您可以执行以下任一操作:

const auto s = static_cast<std::uint8_t>(array.size());
Run Code Online (Sandbox Code Playgroud)

或这个:

const std::uint8_t s = array.size();
Run Code Online (Sandbox Code Playgroud)

或这个(但请不要):

const auto s = std::uint8_t( array.size() );
Run Code Online (Sandbox Code Playgroud)

我建议这样:

const auto s = static_cast<std::uint8_t>(array.size());
Run Code Online (Sandbox Code Playgroud)

运行示例