如何使静态映射<字符串,>作为模板类的成员?
How to make a static map<string, TNested> as member of template class?
以下代码编译失败,出现以下错误:
错误C2923 'std::map': 'Foo::CacheEntry'无效形参'_Ty'的模板类型参数
为什么Foo::CacheEntry不是有效的模板类型参数?
#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>();
Foo<argb>::CacheEntry
是一个依赖名称,因此您需要告诉编译器它使用typename
关键字命名类型:
template<int argb>
std::map<std::string, typename Foo<argb>::CacheEntry> Foo<argb>::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 {};
相关文章:
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 静态数据成员的问题-修复链接错误会导致编译器错误
- 将公共但非静态的成员函数与ALGLIB集成
- 私有类型的静态常量成员
- 如何在C++中使用非静态成员函数作为回调函数
- (C++)为什么静态成员可以在初始化之前使用
- 添加静态constexpr成员是否会更改结构/类的内存映射
- 静态数据成员模板专用化的实例化点在哪里
- 在派生类中绑定非静态模板化成员函数
- 类的全局对象和静态成员
- 在作为静态成员包含在另一个类中的类的构造函数中使用 cout
- 模板化类中静态成员的延迟初始化
- 枚举成员与静态 int 成员?
- 使用静态成员声明类时遇到问题
- C++ 模板类型的静态 lambda 成员的构造
- 初始化与类类型相同的静态成员(静态初始化顺序问题)
- 成员静态回调函数的外部"C"
- 成员静态函数中的C++静态变量
- 将pthread_mutex_t和pthread_cond_t作为类成员静态变量的任何缺点
- 初始化私有成员静态常量数组