使用auto作为模板参数

0 c++ templates auto c++11

我正在尝试使用GCC 4.7.1编译以下-std=c++11标志:

std::map<std::string, auto> myMap;
Run Code Online (Sandbox Code Playgroud)

我正在尝试创建一个对象来包含大量各种类型的Json数据(int string,bool)以及子结构(list,map),所以我无法在编译时声明字段值的类型时间,所以我以为我会使用auto关键字.

但是,当我尝试编译它时,我得到以下内容

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>’
Run Code Online (Sandbox Code Playgroud)

有没有一种特殊的方法可以auto用作模板参数,还是只是不可能?

ron*_*nag 7

我认为你要找的是boost :: any.

std::map<std::string, boost::any> myMap;
Run Code Online (Sandbox Code Playgroud)

auto 在编译期间进行评估,不能用作动态运行时类型.

  • [`boost :: variant`](http://www.boost.org/doc/libs/1_51_0/doc/html/variant.html)对JSON来说是一个更好的建议,因为数量非常有限JSON数据结构可以具有的类型. (7认同)