使用auto作为模板参数

Using auto as a template parameter

本文关键字:参数 auto 使用      更新时间:2023-10-16

我正试图使用GCC 4.7.1并设置-std=c++11标志来编译以下内容:

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

我正试图创建一个对象来包含大量各种类型的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>’

有没有一种特殊的方法可以使用auto作为模板参数,或者这是不可能的?

我认为您想要的是boost::any。

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

auto是在编译时评估的,不能用作动态运行时类型。

这根本不可能。auto背后的类型必须从某种东西中推导出来。最接近这一点的方法是使用带有某种表达式的decltype

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

但这里的decltype解析为一个类型,您不能在编译时更改它。