2
#include <map>
#include <list>

template < typename K, typename  V>
class LruCache
{
private:
    typedef std::pair< K, V > EntryPair;
    typedef std::list< EntryPair > CacheList;
    typedef std::map< K, CacheList::iterator > CacheMap;

public:
    LruCache(){}
    ~LruCache(){}
};

如果我尝试简单

LruCache 缓存;

我收到以下编译错误:

LruCache.h:17:46: error: type/value mismatch at argument 2 in template parameter list for ‘template<class _Key, class _Tp, class _Compare, class _Alloc> class std::map’
LruCache.h:17:46: error:   expected a type, got ‘LruCache<K, V>::CacheList:: iterator’
LruCache.h:17:46: error: template argument 4 is invalid

但是,如果我定义没有模板类型的类。IE

class LruCache
{
private:
    typedef std::pair< int, int > EntryPair;
    typedef std::list< EntryPair > CacheList;
    typedef std::map< int, CacheList::iterator > CacheMap;

public:
    LruCache(){}
    ~LruCache(){}
};

它编译得很好。

4

2 回答 2

2

用作typename

typedef std::map< K,typename CacheList::iterator > CacheMap;
                   //^^^^^^

因为iterator是模板参数的依赖名称。它的取决于CacheListwhich 又取决于which 实际上是模板参数。这就是为什么这里需要它告诉编译器实际上是嵌套类型,而不是Ttypenameiteratorstatic

但是,在第二种情况下,它不是从属名称。

阅读 Johannes 的详细解释:

于 2011-06-22T00:58:49.780 回答
1

替换这个:

typedef std::map< K, CacheList::iterator > CacheMap;

有了这个:

typedef std::map< K, typename CacheList::iterator > CacheMap;

看到这个问题。基本上,编译器在实例化之前不知道(不知道模板参数)CacheList::iterator是类型还是值,并且禁止将决定推迟到那个时候,所以它假定它是一个值,你必须给它一个否则“提示”。

于 2011-06-22T01:00:32.847 回答