Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't you use auto as a template type argument (e.g. std::array<auto, 5>)?

Tags:

c++

c++11

stl

Why is this not allowed, for example:

std::array<auto, 5> myArray {

};

It would make my life so much easier, as I would be allowed to store multiple data-types inside the array. I'm sure there's a logical explanation, just wondered what it was.

like image 270
Phorce Avatar asked Sep 09 '13 15:09

Phorce


2 Answers

auto is used to deduce one type from an expression. Using your suggested syntax would not help because exactly one type can be stored in a container. If you need a way to store any type in the container, take a look at boost::any, so you can use

std::array<boost::any, 5> myArray;
like image 79
cdmh Avatar answered Nov 15 '22 07:11

cdmh


auto is not some sort of magical flexible data type that can store any type of data. auto is a mere compiler keyword that tells the compiler that it has to deduce the specific type automatically. The type is deducted at compile time, meaning that auto is implicitly replaced with a specific type. One specific type. There's no way auto would somehow help you to store different types of data in the same array.

And in order for the actual type to be deducible, the compiler must have enough information to deduce it. In your example the relationship between the auto and the data that must be used to perform deduction (the initializers in the {} list) is not known to the compiler, which is why auto does not work in this context.

For example (borrowing the example from the comments), when you write something like this

auto a[] = { 1, 2, 3, 4, 5 };

the entire declaration is built entirely from core language constructs. The compiler immediately knows that the values in {} are initializers for array elements, whose type is described by keyword auto. So, the meaning of auto is easy to define using the core language concepts.

But in a declaration like

std::array<auto, 5> myArray  = { 1, 2, 3, 4, 5 };

the template std::array is seen by the compiler proper as a user-defined data type. The relationship between the values in {} and template arguments is also user-defined and hidden inside the implementation of std::array. It can be arbitrarily complex. It is not even known whether such relationship exists. And this is why it generally not possible to derive the actual type of auto is such cases.

like image 34
AnT Avatar answered Nov 15 '22 07:11

AnT