Re: initialize reference
In article <1153777669.706631.247520@75g2000cwc.googlegroups.com>, jean
<jean.shu@gmail.com> wrote:
Hi,
I have the following code. Basically, I want to insert to different map
depends on m_bDefaultTag . I know I need to initialize updateTags. But
how? Is there a way to achieve my goal? Thanks.
class tag_entry
{
string m_name;
int value;
}
void MyFunc()
{
std::map<std::string, tag_entry >& customTags =
GetCustomTags();
std::map<std::string, tag_entry >& defineTags =
GetDefineTags();
std::map<std::string, tag_entry >& updateTags;
if( m_bDefaultTag ) {
updateTags = defineTags;
}
else {
updateTags = customTags;
}
customTags.insert( mapElement );
}
use the ternary ? : operator like this.
void MyFunc()
{
std::map<std::string,tag_entry> &customTags = GetCustomTags();
std::map<std::string,tag_entry> &defineTags = GetDefineTags();
std::map<std::string,tag_entry> &updateTags =
m_bDefaultTag ?
defineTags :
customTags;
}
or use a pointer instead of a reference until which map to use is
determined and then create the reference by dereferencing the pointer.
void MyFunc()
{
std::map<std::string,tag_entry> &customTags = GetCustomTags();
std::map<std::string,tag_entry> &defineTags = GetDefineTags();
std::map<std::string,tag_entry> *p;
if(m_bDefaultTag)
p = &defineTags;
else
p = &customTags;
std::map<std::string,tag_entry> &uptadeTags = *p;
}
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]