C++ 如何制作静态地图<;字符串,TNested>;作为模板类的成员?
以下代码无法编译,出现以下错误: 错误C2923“std::map”:“Foo::CacheEntry”不是有效的 参数“\u Ty”的模板类型参数 为什么Foo::CacheEntry不是有效的模板类型参数C++ 如何制作静态地图<;字符串,TNested>;作为模板类的成员?,c++,templates,static,C++,Templates,Static,以下代码无法编译,出现以下错误: 错误C2923“std::map”:“Foo::CacheEntry”不是有效的 参数“\u Ty”的模板类型参数 为什么Foo::CacheEntry不是有效的模板类型参数 #include "stdafx.h" #include <iostream> #include <map> #include <string> template<int arga> class Foo { private: cla
#include "stdafx.h"
#include <iostream>
#include <map>
#include <string>
template<int arga>
class Foo {
private:
class CacheEntry {
public:
int x;
};
static std::map<std::string, CacheEntry> cache;
};
template<int argb>
std::map<std::string, Foo<argb>::CacheEntry> Foo<argb>::cache = std::map<std::string, Foo<argb>::CacheEntry>();
#包括“stdafx.h”
#包括
#包括
#包括
模板
福班{
私人:
类缓存项{
公众:
int x;
};
静态std::map缓存;
};
模板
std::map Foo::cache=std::map();
Foo::CacheEntry
是一个依赖名称,因此您需要告诉编译器它使用typename
关键字命名类型:
template<int argb>
std::map<std::string, typename Foo<argb>::CacheEntry> Foo<argb>::cache{};
模板
std::map Foo::cache{};
请注意,复制初始化是非常冗余的,您可以只使用值初始化
如果您发现自己需要相当数量的该类型,您可以为其制作一个别名:
template<int arga>
class Foo {
private:
class CacheEntry {
public:
int x;
};
using CacheMap = std::map<std::string, CacheEntry>;
static CacheMap cache;
};
template<int argb>
typename Foo<argb>::CacheMap Foo<argb>::cache {};
模板
福班{
私人:
类缓存项{
公众:
int x;
};
使用CacheMap=std::map;
静态缓存映射缓存;
};
模板
typename Foo::CacheMap Foo::cache{};
std::map
-尽管如此,VisualStudio的错误消息并不那么简单。