我有一个模板类,其中使用typedef声明一个映射,如下所示:
#include <map>
template <typename T> class LocalStub {
typedef std::map<T, T> QueryMap;
typedef std::pair<T, T> QueryPair;
typedef QueryMap::iterator QueryMapIterator;
public:
LocalStub();
~LocalStub();
void AddQuery(const T &, const T &);
const T &Answer(const T &) const;
private:
QueryMap _queryMap;
};
../src/LocalStub/include/localstub.hpp:12: error: declaration of 'class T'
../src/LocalStub/include/localstub.hpp:11: error: shadows template parm 'class T'
../src/LocalStub/include/localstub.hpp:13: error: template declaration of 'typedef'
../src/LocalStub/include/localstub.hpp:14: error: declaration of 'class T'
../src/LocalStub/include/localstub.hpp:11: error: shadows template parm 'class T'
../src/LocalStub/include/localstub.hpp:15: error: template declaration of 'typedef'
../src/LocalStub/include/localstub.hpp:16: error: declaration of 'class T'
../src/LocalStub/include/localstub.hpp:11: error: shadows template parm 'class T'
../src/LocalStub/include/localstub.hpp:17: error: template declaration of 'typedef'
../src/LocalStub/include/localstub.hpp:26: error: 'QueryMap' does not name a type
我在做什么错?我不明白为什么会收到该错误。
答案 0 :(得分:2)
您忘了用typename
写关键字QueryMapIterator
。这是更新的版本:
template <typename T> class LocalStub {
typedef std::map<T, T> QueryMap;
typedef std::pair<T, T> QueryPair;
typedef typename QueryMap::iterator QueryMapIterator;
public:
LocalStub();
~LocalStub();
void AddQuery(const T &, const T &);
const T &Answer(const T &) const;
private:
QueryMap _queryMap;
};
之所以有此要求,是因为编译器此时不知道QueryMapIterator
是描述成员变量还是嵌套类型
答案 1 :(得分:1)
TL; DR-typedef typename QueryMap::iterator QueryMapIterator;
更长的版本:
QueryMap::iterator
是dependant name,因此要求typename
之前使用typedef
。从属名称问题来自以下事实:在模板构造type::something
中,something
可以引用类型,值或函数,如下例所示:
template<class T>
struct foo{
void bar(){ T::something; }
};
struct baz{
using something = int;
};
struct bez{
static const int something = 0;
};
因此,如果您传递的名称涉及类型,则需要typename
才能向编译器提供其他信息。