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
?
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.
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.
You may use
std::tuple_size
: