gpt4 book ai didi

c++ - 无法为我的 LruCache 类定义模板化类型

转载 作者:太空狗 更新时间:2023-10-29 12:07:18 25 4
gpt4 key购买 nike

#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

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

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

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

它编译得很好。

最佳答案

使用 typename 作为:

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

这是因为 iterator 是模板参数的依赖名称。它的值取决于 CacheList 而后者又取决于 T 而实际上是一个模板参数。这就是为什么 typename 在这里需要它,它告诉编译器 iterator 实际上是一个嵌套的 type,而不是 静态

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

阅读 Johannes 的详细解释:

关于c++ - 无法为我的 LruCache 类定义模板化类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6433741/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com