Get size of std::array without an instance

5.7k views Asked by At

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?

6

There are 6 answers

2
Jarod42 On BEST ANSWER

You may use std::tuple_size:

std::tuple_size<decltype(Foo::bar)>::value
5
skypjack On

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.

7
Happy On

You can use like:

sizeof Foo().bar
5
Waxrat On

You could do it the same as for legacy arrays:

sizeof(Foo::bar) / sizeof(Foo::bar[0])
1
Gilson PJ On

Use:

sizeof(Foo::bar) / sizeof(int)
3
Willy Goat On

You could give Foo a public static constexpr member.

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

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