Get size of std::array without an instance

C++C++11Stdarray

C++ Problem Overview


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?

C++ Solutions


Solution 1 - C++

You may use std::tuple_size:

std::tuple_size<decltype(Foo::bar)>::value

Solution 2 - C++

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.

Solution 3 - C++

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.

Solution 4 - C++

You could do it the same as for legacy arrays:

sizeof(Foo::bar) / sizeof(Foo::bar[0])

Solution 5 - C++

Use:

sizeof(Foo::bar) / sizeof(int)

Solution 6 - C++

You can use like:

sizeof Foo().bar

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionChronoTriggerView Question on Stackoverflow
Solution 1 - C++Jarod42View Answer on Stackoverflow
Solution 2 - C++skypjackView Answer on Stackoverflow
Solution 3 - C++Willy GoatView Answer on Stackoverflow
Solution 4 - C++WaxratView Answer on Stackoverflow
Solution 5 - C++Gilson PJView Answer on Stackoverflow
Solution 6 - C++HappyView Answer on Stackoverflow