I'm relatively new to using the auto type, but I have been seeing it a lot in my code base at work lately. One of the reasons I don't like using it is because I often forward declare things, which as far as I know cannot be done with auto. I was under the impression this was because types are determined at compile time.
What I am seeing a lot of is this, and I don't understand why you would ever do it.
auto value = 0;
if ( condition 1 )
{
value = mValueStore.getValue(foo::bar::value);
}
else
{
value = mValueStore.getValue(foo::bar::value2);
}
Is there a justification for doing this?
Either using auto
or int
in this case is not perfect - because type of value is "disconnected" from the type that method returns. Probably int
is little bit better in this case because type of value
is clear, with auto
it can give wrong impression. Better solution could be:
decltype(mValueStore.getValue(foo::bar::value)) value = 0;
but that is verbose so even better using auto
with conditional operator
auto value = mValueStore.getValue( condition ? foo::bar::value : foo::bar::value2);
if possible to rewrite expression like that so value
would always have the same type as that method returns.