Strange Compiler Error, stating that my iterator is undefined

1.5k views Asked by At

I'm trying to create a template function which will iterate through the map's specified key/value pairs and check to see if there exists any keys specified in the function's parameters.

The implementation looks as follows:

Code

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

Yet, for whatever reason, I can't seem to figure out why my code won't compile. I get these errors instead:

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

I've ran into these before, but these usually have been due to mistakes I've made which are easy to spot. What could be going on here?

1

There are 1 answers

2
mwigdahl On BEST ANSWER

Pretty sure you need a typename qualifier:

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 explains in considerable detail.

Effectively, the compiler knows that there could potentially be a specialization of std::map< Key, Value > for certain values of Key and Value which could contain a static variable named iterator. So it needs the typename qualifier to assure it that you are actually referring to a type here and not some putative static variable.