Rajendra Uppal
Rajendra Uppal

Reputation: 19914

Why can't I create an array of automatic variables?

In C++0x (ohh! read C++11), we have automatic type inference. One thing which made me curious was that I can't create an array of auto variables. For example:

auto A[] = {1, 2, 3, 4}; // Error!

Any ideas why this might have been disallowed?

Upvotes: 16

Views: 4086

Answers (2)

Puppy
Puppy

Reputation: 146910

Because {1, 2, 3, 4} is purely a syntactic construct- it is not an expression and does not have a type. Therefore, auto cannot deduce its type from it.

Upvotes: 5

pmr
pmr

Reputation: 59811

auto deduces every brace-enclosed initializer list to a std::initializer_list<T>. (See §7.1.6.4.6 including the example). Unfortunately you cannot initialize an array or even std::array from a std::initializer_list once you have obtained it, but you can use a std::vector.

#include <vector>
#include <array>
#include <initializer_list>

int main()
{
  auto x = {1,2,3};
  std::array<int, 3> foo1 = x; // won't work for whatever reason
  std::vector<int> foo2 = x; // works as expected
  return 0;
}

Of course this defeats the whole purpose of what you are trying to do.

I tried writing a work around called make_array but had to realize that this cannot ever work as the size of an initializer_list isn't part of its template arguments and so you only instantiate one make_array template for each T. This sucks.

template<typename T> 
auto make_array(const std::initializer_list<T>& x) 
     -> std::array<T, x.size()> { } // maaah

Well, apparently you can go for the variadic-template hack mentioned here How do I initialize a member array with an initializer_list?

Upvotes: 12

Related Questions