Pepe
Pepe

Reputation: 6480

Why is this map<int, auto> not allowed?

I am trying to implement a heterogeneous map in C++. I know that this has been previously discussed before but I was wondering why the following is not allowed:

map<int, auto> myMap;

Is there anyway in which I could make insertion into a map simple without having to resort to (void*) pointers?

I was thinking about eventually being able to do something like this:

vector<int> v;
myMap.insert(make_pair<int, int>(1,12334));
myMap.insert(make_pair<int, vector<int>)(2, v));

Is this possible? or are my efforts futile?

Thanks

Upvotes: 3

Views: 479

Answers (4)

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272487

It's not allowed because it's not meaningful. You can't use a value from this hypothetical construct with storing some meta-information about what type is stored in each instance (and a big switch statement), which is what e.g. Boost Variant does.

Upvotes: 2

Aasmund Eldhuset
Aasmund Eldhuset

Reputation: 37950

auto does not mean "this can be any type". It is a special keyword that can only be used to declare variables, and its meaning is "the type of this variable is the same as the type of the expression used to initialize it". The type of an auto variable is as unchangeable as the type of any other declared variable; the only difference is that you don't have to spell out the name of the type. Since auto is not a type, but just syntactic sugar for simplifying declarations, it cannot be used as a template parameter.

Upvotes: 19

Mat
Mat

Reputation: 206689

You're looking for an heterogeneous map, not an homogeneous one. There are quite a few hits on google when you use that term, for example Revisiting Heterogeneous Containers.

Upvotes: 2

Blindy
Blindy

Reputation: 67380

Just thing of extracting information from that thing, what would its type be?

You want something like variant or any from the boost library. They are still strongly typed, but with heavy use of templates.

Upvotes: 5

Related Questions