Вы можете захотеть 2 перегрузки:
DATA * lookup( DataList & theMap, int key )
{
DataList::iterator iter = theMap.find( key );
if( iter != theMap.end() )
{
return &iter->second;
}
else
return NULL;
}
и
const DATA * lookup( const DataList & theMap, int key )
{
DataList::const_iterator iter = theMap.find( key );
if( iter != theMap.end() )
{
return &iter->second;
}
else
return NULL;
}
Конечно, это означает дублирование кода.Так что может быть хорошим кандидатом на конст-каст.
DATA * lookup( DataList & theMap, int key )
{
return const_cast<DATA *>(lookup( const_cast<const DataList&>(theMap), key));
}
, и вы можете сделать его универсальным шаблоном:
template< typename Key, typename Value >
const Value * mapValueLookup( const std::map<Key, Value>& theMap, Key key )
{
typename std::map<Key, Value>::const_iterator iter = theMap.find(key);
if( iter != theMap.end() )
{
return &iter->second;
}
else
return NULL;
}
template< typename Key, typename Value >
Value * mapValueLookup( std::map<Key, Value>& theMap, Key key )
{
return const_cast<Value*>( mapValueLookup
( const_cast<const std::map<Key, Value> &>(theMap),
key ) );
}