Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the number of elements in std::array at compile time

Tags:

c++

Is the following a valid C++ code, and why not?

std::array<std::string, 42> a1; std::array<int, a1.size()> a2; 

It doesn't compile in GCC 4.8 (in C++11 mode). There is a simple but inelegant workaround:

std::array<std::string, 42> a1; std::array<int, sizeof(a1)/sizeof(a1[0])> a2; 

So clearly the compiler can figure out the number of elements in std::array. Why std::array::size() is not a constexpr static function?

EDIT: I have found another workaround:

std::array<std::string, 42> a1; std::array<int, std::tuple_size<decltype(a1)>::value> a2; 
like image 338
robson3.14 Avatar asked May 31 '13 21:05

robson3.14


1 Answers

array<T>::size() is constexpr, but you can't use it in this way because a1 isn't a constexpr value. Additionally, it can't be constexpr because string isn't a literal type.

However, you can work around this if you want, by deducing the size_t template parameter. Example:

#include <string> #include <array> #include <iostream> using namespace std;  template<typename> struct array_size; template<typename T, size_t N> struct array_size<array<T,N> > {     static size_t const size = N; };  array<string, 42> a1; array<string, array_size<decltype(a1)>::size> a2;  int main() {     cout << a2.size() << endl; } 
like image 109
Adam H. Peterson Avatar answered Oct 09 '22 11:10

Adam H. Peterson