无法访问模板函数内的迭代器

w00*_*row 2 c++ templates map

我有以下代码

#include <map>
template <typename Value>
static void Get(std::map<int, Value> & map)
{
    typename std::map<int, Value>::const_iterator it;
    it _it = map.find(1);
}
void main()
{
    std::map<int,std::string> _map;
    _map.insert(std::pair<int,std::string>(1, "1"));
    Get<std::string>(_map);
}
Run Code Online (Sandbox Code Playgroud)

我收到了该行的错误

it _it = map.find(1);
Run Code Online (Sandbox Code Playgroud)

为什么这样?

bil*_*llz 6

如果您打算定义it为类型,则需要typedef

typedef typename std::map<int, Value>::const_iterator it;
Run Code Online (Sandbox Code Playgroud)

如果你想定义it为变量:

typename std::map<int, Value>::const_iterator it;
it  = map.find(1);
Run Code Online (Sandbox Code Playgroud)

或者只写:

auto it = map.find(1);
Run Code Online (Sandbox Code Playgroud)

另外,void main()应该是int main().

  • 或者,只需编写`auto it = map.find(1);`并暂时忘记typename和typedef. (2认同)