【问题标题】:Strange Compiler Error, stating that my iterator is undefined奇怪的编译器错误,说明我的迭代器未定义
【发布时间】:2012-01-27 22:48:56
【问题描述】:

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

实现如下:

代码

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

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

【问题讨论】:

标签: c++ scope compiler-errors expected-exception


【解决方案1】:

很确定您需要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 解释得很详细。

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

【讨论】:

  • @Holland 该代码在运行之前可能需要进行更多清理。见ideone.com/lcsQB
  • 好点。我刚刚解决了他报告的特定错误。
猜你喜欢
  • 2013-08-19
  • 1970-01-01
  • 2016-01-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多