其他分享
首页 > 其他分享> > c – 奇怪的编译器错误,声明我的迭代器未定义

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

作者:互联网

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

实现如下:

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;
}

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

error: expected ';' before 'it'
error: 'it' was not declared in this scope

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

解决方法:

很确定你需要一个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;
}

This article详细解释.

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

标签:c,scope,compiler-errors,expected-exception
来源: https://codeday.me/bug/20190902/1791586.html