3

我正在尝试创建一个模板函数,它将遍历地图的指定键/值对并检查函数参数中是否存在指定的任何键。

实现如下所示:

代码

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

我以前遇到过这些,但这些通常是由于我犯的容易发现的错误造成的。这里会发生什么?

4

1 回答 1

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

这篇文章解释得很详细。

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

于 2012-01-27T22:52:37.510 回答