模板std :: map :: iterator实例化

时间:2012-12-06 12:22:50

标签: c++ templates map iterator

  

可能重复:
  Where and why do I have to put the “template” and “typename” keywords?
  map iterator in template function unrecognized by compiler

我有一个模板函数,其中包含std::map::iterator实例化 -

template <class B , class C> 
C getValue (B& myMap , C returnType) {
    map<string,C>::iterator it = myMap.find(var);
    // implementation ...
}

并提示错误 -

In function ‘C getValue(char*, B&, C)’:
error: expected ‘;’ before ‘it’
error: ‘it’ was not declared in this scope

我该如何正确使用它?

1 个答案:

答案 0 :(得分:3)

这是一种依赖类型,因此您需要typename

typename map<string,C>::iterator it = myMap.find(var);

有关更多的更多详情,请参阅Where and why do I have to put the "template" and "typename" keywords?

Zoidberg'所述,C ++ 11有auto,它指示编译器推断出类型。有关简要概述(以及其他一些功能),请参阅Elements of Modern C++ Style