user360907
user360907

Reputation:

Using auto as a template parameter

I'm attempting to compile the following using GCC 4.7.1 with the -std=c++11 flag set:

std::map<std::string, auto> myMap;

I'm attempting to create an object to contain a large amount of Json data of various types (int string, bool) as well as sub-structures (list, map) so I can't declare the type of the field value at compile time, so I thought I'd use the auto keyword for it.

However, when I try to compile it, I get the following

error: invalid use of ‘auto’
error: template argument 2 is invalid
error: template argument 4 is invalid
error: unable to deduce ‘auto’ from ‘<expression error>’

Is there a special way to use auto as a template argument, or is it just not possible?

Upvotes: 0

Views: 1604

Answers (2)

ronag
ronag

Reputation: 51255

I think what you are looking for is boost::any.

std::map<std::string, boost::any> myMap;

auto is evaluated during compile time and cannot be used as a dynamic run-time type.

Upvotes: 7

juanchopanza
juanchopanza

Reputation: 227390

It is simply not possible. The type behind auto has to be deduced from something. The closest you can get to that is using decltype with some expression.

std::map<std::string, decltype(some expression)> myMap;

but decltype here resolves to a type, which you cannot just change at compile time.

Upvotes: 3

Related Questions