Re: Template to insert into a map? Is this really necessary?
"Old Wolf" <oldwolf@inspire.net.nz> wrote in message
news:1183599078.239751.212430@i13g2000prf.googlegroups.com...
On Jul 5, 12:49 pm, "Jim Langston" <tazmas...@rocketmail.com> wrote:
template<class K, class D>
D& InsertToMap( K& Key, D& Data, std::map<K, D>& Map )
The usage:
DropdownBox& ThisBox = InsertToMap( std::string("RoteDots"),
DropdownBox(Parent, IDC_RoteDots ), Dropdowns );
This is an error; you can't bind a temporary to
a non-const reference. Either switch your compiler
to conforming mode, or post your exact code.
Dang, I forgot to change from Warning level 3 to Warning level 4 when I
created this project. With W4 it does indeed say it's non conforming. Hmm.
Also, why would you want to return a reference
to the input data. It doesn't make any logical
sense to do anything with it once a copy of it
has been put into the map.
Because I am creating the instance in the map, then I need to do things with
it (add entries, etc..).
I.E.
DropdownBox& RoteDots = InsertToMap( Dropdowns, std::string("RoteDots"),
DropdownBox( Parent, IDC_RoteDots ) );
RoteDots.AddEntry( "0" );
RoteDots.AddEntry( "1" );
RoteDots.AddEntry( "2" );
RoteDots.AddEntry( "3" );
RoteDots.AddEntry( "4" );
RoteDots.AddEntry( "5" );
which even though still a bit ugly, is better than the first one
You seem to have omitted trying:
Dropdowns.insert( std::make_pair(
std::string("RoteDots"), DropDownBox( Parent, IDC_RoteDots ) ) );
(the whole point of std::make_pair is that you do
not explicitly specify the template parameters).
I can fix that in my template.
If you dont mind using a function then the obvious is
(replace Ddmap with the typedef you've defined for
your map):
void insert_dropdown( Ddmap &map,
Ddmap::key_type const &key, Ddmap::value_type const &value )
{
map.insert( std::make_pair(key, value) );
}
and then call:
insert_map( Dropdowns, "RoteDots, DropDownBox(foo,bar) );
You could even go as far as:
void insert_dropdown( Ddmap &map,
Ddmap::key_type const &key, Foo *foo, Bar *bar )
{
map.insert( std::make_pair(key, DropdownBox(foo,bar)) );
}
Well, without the need to retrieve a reference to the added entry, it is
eaiser by a lot of ways, but I need to retrieve a reference to the entry
just added.