Question

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?

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top