Consider the following snippet of code:
#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;
}
While it compiles using gcc 9.3.0 (the default on Ubuntu 20.04), it fails with gcc 11.2.0 (built from sources) with the following error message:
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
Running example
Besides the fact that it does not make much sense, I can't find where is the error, can you help me?
In C++, we use sizeof() operator to find the size of desired data type, variables, and constants. It is a compile-time execution operator. We can find the size of an array using the sizeof() operator as shown: // Finds size of arr[] and stores in 'size' int size = sizeof(arr)/sizeof(arr[0]);
array::size() in C++ STL The introduction of array class from C++11 has offered a better alternative for C-style arrays. size() function is used to return the size of the list container or the number of elements in the list container.
The 'sizeof' operator returns size of a pointer, not of an array, when the array was passed by value to a function. In this code, the A object is an array and the sizeof(A) expression will return value 100. The B object is simply a pointer.
std::array is a container that encapsulates fixed size arrays. This container is an aggregate type with the same semantics as a struct holding a C-style array T[N] as its only non-static data member. Unlike a C-style array, it doesn't decay to T* automatically.
It appears to be a bug in:
It works fine in:
To work around, you can do either this:
const auto s = static_cast<std::uint8_t>(array.size());
or this:
const std::uint8_t s = array.size();
or this (but please don't):
const auto s = std::uint8_t( array.size() );
I would suggest this:
#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;
}
Running example
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With