Template to insert into a map? Is this really necessary?
I'm working on a program, and at one time I find it necessary to load
classes into a map. Now, these classes don't have default constructors, so
I can't retrieve them using
MyMap[MyKey].
So I wound up with a real ugly line:
DropdownBox& ThisBox = (Dropdowns.insert( Dropdowns.begin(),
std::make_pair<std::string, DropdownBox>( "RoteDots", DropdownBox( Parent,
IDC_RoteDots ) ) ))->second;
My map is fairly simple.
std::map<std::string, DropdownBox> Dropdowns;
Well, I tried to improve it a little, and came up with
std::map<std::string, DropdownBox>::iterator it = Dropdowns.insert(
Dropdowns.begin(), std::make_pair<std::string, DropdownBox>( "RoteDots",
DropdownBox( Parent, IDC_RoteDots ) ) );
DropdownBox& ThisBox = it->second;
but that's still ugly. So I decided to make a template function to help.
The template itself is kinda messy, but makes the code easier.
The template:
template<class K, class D>
D& InsertToMap( K& Key, D& Data, std::map<K, D>& Map )
{
std::map<K, D>::iterator it = Map.insert( Map.begin(), std::make_pair<K,
D>( Key, Data ) );
return it->second;
}
The usage:
DropdownBox& ThisBox = InsertToMap( std::string("RoteDots"), DropdownBox(
Parent, IDC_RoteDots ), Dropdowns );
which even though still a bit ugly, is better than the first one IMO.
Of course I could always insert into the map then use .find() but I've
alwasy found that bothersome in itself.
Any opionions?