Question: Get size of std::array without an instance

Question

Get size of std::array without an instance

Answers 6
Added at 2016-12-27 13:12
Tags
Question

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?

Answers
nr: #1 dodano: 2016-12-27 13:12

You may use std::tuple_size:

std::tuple_size<decltype(Foo::bar)>::value
nr: #2 dodano: 2016-12-27 13:12

You can use like:

sizeof Foo().bar
nr: #3 dodano: 2016-12-27 13:12

You could do it the same as for legacy arrays:

sizeof(Foo::bar) / sizeof(Foo::bar[0])
nr: #4 dodano: 2016-12-27 14:12

Use:

sizeof(Foo::bar) / sizeof(int)
nr: #5 dodano: 2016-12-27 14:12

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.

nr: #6 dodano: 2016-12-27 17:12

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.

Source Show
◀ Wstecz