2

The following code fails to compile with the following error:

Error C2923 'std::map': 'Foo::CacheEntry' is not a valid template type argument for parameter '_Ty'

Why is Foo::CacheEntry not a valid template type argument?

#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>();
Edward J Brown
  • 333
  • 1
  • 5
  • 17

1 Answers1

2

Foo<argb>::CacheEntry is a dependent name, so you need to tell the compiler that it names a type with the typename keyword:

template<int argb>
std::map<std::string, typename Foo<argb>::CacheEntry> Foo<argb>::cache{};

Note that the copy-initialization is pretty redundant, you can just use value-initialization.

If you find yourself needing that type a fair amount, you can make an alias for it:

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 {};
TartanLlama
  • 63,752
  • 13
  • 157
  • 193