Using auto as a template parameter

試著忘記壹切 提交于 2019-12-23 06:01:45

问题


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?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/12176972/using-auto-as-a-template-parameter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!