2

I have the following line of code which works great:

const auto& dict = m_DictionaryAbbreviationsAndEnglish.Content;

Now I wanted to introduce an "if-then" clause, but the compiler tells me "Can't deduce 'auto' type (initalizer required):

const auto& dict;

if (uSkipAbbreviationsAndEnglish)
{
    dict = m_DictionaryNoAbbreviationsNoEnglish.Content();
}
else
{
    dict = m_DictionaryAbbreviationsAndEnglish.Content();
}

However, when I initialize it like this...

const auto& dict=NULL;

..., I'm unable to assign "dict" using such code:

dict = m_DictionaryNoAbbreviationsNoEnglish.Content();

The error is "Expression must be a modifiable lValue."

Can anybody tell me how to do this correctly?

Thank you.

ps: Content is this:

map<wstring,wstring> &clsTranslations::Content()
{
    return m_content;
}
tmighty
  • 10,734
  • 21
  • 104
  • 218
  • Don't use `auto` here, it's probably not worth it. – DeiDei Mar 19 '17 at 17:16
  • 1
    You cannot reassign a reference. Take a look at [here](http://stackoverflow.com/questions/728233/why-are-references-not-reseatable-in-c). – Shibli Mar 19 '17 at 17:17
  • Constants have to be initialized – Sniper Mar 19 '17 at 17:40
  • 1
    auto gets its type from its initialization. It needs to be initialized in the declaration in order to infer type. When you assign NULL to it, it's getting the null type, which might be `int`, `unsigned int` or `nullptr_t`, among really pretty much anything else, as long as it evaluates to 0 and can be converted to a pointer of any type (before C++11. After C++11, it needs to be `nullptr_t`). Also, as others have said, constants have to be initialized on declaration, as by definition, they are constant, and can not be changed after declaration. – Taywee Mar 19 '17 at 17:41

1 Answers1

6

That is what the conditional operator is for:

const auto& dict = uSkipAbbreviationsAndEnglish ? 
                   m_DictionaryNoAbbreviationsNoEnglish.Content() : 
                   m_DictionaryAbbreviationsAndEnglish.Content();
juanchopanza
  • 223,364
  • 34
  • 402
  • 480