模板标准::映射为类成员

template std::map as class member

本文关键字:成员 映射 标准      更新时间:2023-10-16

我需要这样的东西作为类成员:

std::map<std::string, std::map<std::string, template<class> T>> m_map;

错误消息:template is not allowed

有人可以帮助我解决这个问题吗?

感谢

您可以从映射的声明中删除template<class>

template<class T>
class A
{
   std::map<std::string, std::map<std::string, T>> m_map;
};

std::map<>需要(具体的)类型参数,但template<class> T不是一个类型,那么std::map<std::string, template<class> T>>就不是一个类型。

不幸的是,"这样的东西"不是一个足够好的规范。

如果您真的是"将字符串映射到(字符串映射到 T)",那么以下内容将是一个合适的、可重用的解决方案:

// Declare a template type "map of string to (map of string to T)"
template <typename T>
using foobar = std::map<std::string, std::map<std::string, T>>;
....
foobar<int> frob;

请参阅 http://ideone.com/YZ6FRa 。

作为会员一次性拍摄,这也是可能的:

template <typename T>
class Foobar {
    std::map<std::string, std::map<std::string, T>> m_map;
};

如果您打算将std::map作为类模板参数std::map实际上需要四个模板参数,其中两个是默认的。

#include <map>
template <template <typename, typename, typename, typename> class T>
void func()
{
}
int main()
{
    func<std::map>();
}

然后你可以键入def:

typedef T<std::string, int, std::less<std::string>, std::allocator<std::pair<const std::string, int>>> my_map;

(可选)std::stringint是传递给函数的模板参数。