代码之家  ›  专栏  ›  技术社区  ›  Eli

编译器无法识别模板函数中的映射迭代器

  •  3
  • Eli  · 技术社区  · 14 年前

    我有以下代码。

    template<class key,class val>
    bool has_key(key chkey,std::map<key,val> map){
      for (std::map<key,val>::iterator it = map.begin(); #line 13 referenced by gcc
          it!=map.end(); ++it){
        if(chkey == it->first) return true;
      }
      return false;
    }
    

    GCC给了我以下错误。

    objects.hpp: In function `bool has_key(key, std::map<key, val, std::less<_Key>,
      std::allocator<std::pair<const _Key, _Tp> > >)':
    objects.hpp:13: error: expected `;' before "it"
    objects.hpp:14: error: `it' was not declared in this scope
    

    不知怎的,“它”没有被初始化,这到底是怎么回事?!

    1 回复  |  直到 14 年前
        1
  •  28
  •   Community CDub    7 年前

    你需要 typename

    for (typename std::map<key,val>::iterator it = map.begin(); #line 13 referenced by gcc
      it!=map.end(); ++it){
    

    另请参见: Why do we need typename here?

    iterator 是从属名称。这是以前问过的。

    g++ "is not a type" error

    C++ Template: 'is not derived from type'

    Trouble with dependent types in templates