This question already has an answer here:
这个问题在这里已有答案:
- Where and why do I have to put the “template” and “typename” keywords? 6 answers
我必须在何处以及为何要使用“模板”和“typename”关键字? 6个答案
I am trying to compile the following code on Linux using gcc 4.2:
我正在尝试使用gcc 4.2在Linux上编译以下代码:
#include <map>
#include <list>
template<typename T>
class A
{
...
private:
std::map<const T, std::list<std::pair<T, long int> >::iterator> lookup_map_;
std::list<std::pair<T, long int> > order_list_;
};
When I compile this class I receive the following message from gcc:
当我编译这个类时,我从gcc收到以下消息:
error: type/value mismatch at argument 2 in template parameter list for ‘template<class _Key, class _Tp, class _Compare, class _Alloc> class std::map’
error: expected a type, got ‘std::list<std::pair<const T, long int>,std::allocator<std::pair<const T, long int> > >::iterator’
error: template argument 4 is invalid
I have removed file names and line numbers , but they all refer to the line declaring the map.
我删除了文件名和行号,但它们都引用了声明地图的行。
When I replace the pair in these expressions with an int or some concrete type, it compiles fine. Can someone please explain to me what I am doing wrong.
当我用int或某些具体类型替换这些表达式中的对时,它编译得很好。有人可以向我解释我做错了什么。
2 个解决方案
#1
You need to write typename
before std::list<...>::iterator
, because iterator
is a nested type and you're writing a template.
您需要在std :: list <...> :: iterator之前编写typename,因为迭代器是嵌套类型,而您正在编写模板。
Edit: without the typename
, GCC assumes (as the standard requires) that iterator
is actually a static variable in list
, rather than a type. Hence the "parameter type mismatch" error.
编辑:没有typename,GCC假定(作为标准要求)迭代器实际上是列表中的静态变量,而不是类型。因此“参数类型不匹配”错误。
#2
Your code needs a "typename" keyword.
您的代码需要“typename”关键字。
std::map<const T, typename std::list<std::pair<T, long int> >::iterator> lookup_map_;
#1
You need to write typename
before std::list<...>::iterator
, because iterator
is a nested type and you're writing a template.
您需要在std :: list <...> :: iterator之前编写typename,因为迭代器是嵌套类型,而您正在编写模板。
Edit: without the typename
, GCC assumes (as the standard requires) that iterator
is actually a static variable in list
, rather than a type. Hence the "parameter type mismatch" error.
编辑:没有typename,GCC假定(作为标准要求)迭代器实际上是列表中的静态变量,而不是类型。因此“参数类型不匹配”错误。
#2
Your code needs a "typename" keyword.
您的代码需要“typename”关键字。
std::map<const T, typename std::list<std::pair<T, long int> >::iterator> lookup_map_;