Given this struct:
struct Foo { std::array<int, 8> bar; };
How can I get the number of elements of the bar
array if I don't have an instance of Foo
?
*(a+1) => Dereferencing to *(&a + 1) gives the address after the end of the last element. *(a+1)-a => Subtract the pointer to the first element to get the length of the array. Print the size. End.
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]);
size() function is used to return the size of the list container or the number of elements in the list container. Syntax : arrayname. size() Parameters : No parameters are passed.
The sizeof() operator can be used to find the length of an array.
You may use std::tuple_size
:
std::tuple_size<decltype(Foo::bar)>::value
Despite the good answer of @Jarod42, here is another possible solution based on decltype
that doesn't use tuple_size
.
It follows a minimal, working example that works in C++11:
#include<array> struct Foo { std::array<int, 8> bar; }; int main() { constexpr std::size_t N = decltype(Foo::bar){}.size(); static_assert(N == 8, "!"); }
std::array
already has a constexpr member function named size
that returns the value you are looking for.
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