如何使静态映射<字符串,>作为模板类的成员?

How to make a static map<string, TNested> as member of template class?

本文关键字:成员 静态 何使 映射 lt 字符串 gt      更新时间:2023-10-16

以下代码编译失败,出现以下错误:

错误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 {};