Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get size of std::array without an instance

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?

like image 623
ChronoTrigger Avatar asked Dec 27 '16 12:12

ChronoTrigger


People also ask

How do you find the size of an array without sizeof?

*(a+1) => Dereferencing to *(&a + 1) gives the address after the end of the last element. *(a+1)-a => Subtract the pointer to the first element to get the length of the array. Print the size. End.

How do I get the size of an array in C++?

In C++, we use sizeof() operator to find the size of desired data type, variables, and constants. It is a compile-time execution operator. We can find the size of an array using the sizeof() operator as shown: // Finds size of arr[] and stores in 'size' int size = sizeof(arr)/sizeof(arr[0]);

How do I find the length of an array in STL?

size() function is used to return the size of the list container or the number of elements in the list container. Syntax : arrayname. size() Parameters : No parameters are passed.

How do you find the length of an array?

The sizeof() operator can be used to find the length of an array.


2 Answers

You may use std::tuple_size:

std::tuple_size<decltype(Foo::bar)>::value 
like image 136
Jarod42 Avatar answered Sep 19 '22 23:09

Jarod42


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.

like image 44
skypjack Avatar answered Sep 19 '22 23:09

skypjack