奇怪的编译器错误,声明我的迭代器未定义

zeb*_*und 3 c++ scope compiler-errors expected-exception

我正在尝试创建一个模板函数,它将迭代映射的指定键/值对,并检查是否存在函数参数中指定的任何键.

实现如下:

template < class Key, class Value >
bool CheckMapForExistingEntry( const std::map< Key, Value >& map, const std::string& key )
{
    std::map< Key, Value >::iterator it = map.lower_bound( key );
    bool keyExists = ( it != map.end && !( map.key_comp() ( key, it->first ) ) );
    if ( keyExists )
    {
        return true;
    }
    return false;
}
Run Code Online (Sandbox Code Playgroud)

然而,无论出于何种原因,我似乎无法弄清楚为什么我的代码无法编译.我得到了这些错误:

error: expected ';' before 'it'
error: 'it' was not declared in this scope
Run Code Online (Sandbox Code Playgroud)

我之前碰到过这些,但这些通常都是由于我所犯的错误很容易发现.这可能会发生什么?

mwi*_*ahl 5

很确定你需要一个typename限定符:

template < class Key, class Value >
bool CheckMapForExistingEntry( const std::map< Key, Value >& map, const std::string& key )
{
    typename std::map< Key, Value >::iterator it = map.lower_bound( key );
    bool keyExists = ( it != map.end && !( map.key_comp() ( key, it->first ) ) );
    if ( keyExists )
    {
        return true;
    }
    return false;
}
Run Code Online (Sandbox Code Playgroud)

本文详细解释了这一点.

实际上,编译器知道可能存在std::map< Key, Value >特定值的特化Key,Value并且可能包含static名为的变量iterator.所以它需要typename限定符来确保它实际上是指这里的类型而不是一些假定的静态变量.