Get std :: array size without instance

Given this structure:

struct Foo { std::array<int, 8> bar; }; 

How can I get the number of elements in the bar array if I don't have a Foo instance?

+46
c ++ c ++ 11 stdarray
Dec 27 '16 at 12:25
source share
6 answers

You can use std::tuple_size :

 std::tuple_size<decltype(Foo::bar)>::value 
+75
Dec 27 '16 at 12:32
source share

Despite @ Jarod42's good answer , here is another possible decltype based decltype that does not use tuple_size .
This 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 called size , which returns the value you are looking for.

+24
Dec 27 '16 at 13:16
source share

You can give the member Foo a public static constexpr .

 struct Foo { static constexpr std::size_t bar_size = 8; std::array<int, bar_size> bar; } 

Now you know the size of the bar from Foo::bar_size , and you have the additional flexibility of naming bar_size something more descriptive if Foo ever has multiple arrays of the same size.

+7
Dec 27 '16 at 16:58
source share

You can do this the same as for legacy arrays:

 sizeof(Foo::bar) / sizeof(Foo::bar[0]) 
+4
Dec 27 '16 at 12:53 on
source share

Using:

 sizeof(Foo::bar) / sizeof(int) 
+1
Dec 27 '16 at 13:02
source share

You can use as:

 sizeof Foo().bar 
-four
Dec 27 '16 at 12:35
source share



All Articles