vendredi 4 mai 2018

A good way to organize a code involving const references with limited scope and templates in C++

So, I have the following piece of code:

if (some_boolean_statement)
{
    const auto& ref = getRef<TYPE_A>(); //getRef returns TYPE_A
    doStuff(ref);
}
else
{
    const auto& ref = getRef<TYPE_B>(); //getRef returns TYPE_B
    doStuff(ref);
}

So, I want to obtain a constant reference ref which depending on some_boolean_statement being true or false is either of TYPE_A or TYPE_B. After that, no matter what, I will call an overloaded function doStuff() that can accept both types as an input.

Now, I don't like that I have to write doStuff(ref); in both branches of the if statement. But since the scope of ref is limited, I don't see a clear way to do it.

Am I missing something really simple? Any advice?

Aucun commentaire:

Enregistrer un commentaire