I am often using the common
if (Value * value = getValue())
{
// do something with value
}
else
{
// handle lack of value
}
Now, I also often do
QString error = someFunctionReturningAnErrorString(arg);
if (!error.isEmpty())
{
// handle the error
}
// empty error means: no error
That's all fine but I would like the error
variable to be scoped to the if
-block. Is there a nice idiom for that? Obviously, I can just wrap the whole part inside another block.
This, obviously, does not work:
if(QString error = someFunctionReturningAnErrorString(arg), !error.isEmpty())
{
// handle the error
}
// empty error means: no error
And unfortunately (but for good reasons) the QString
cannot be converted to bool, so this does not work either:
if(QString error = someFunctionReturningAnErrorString(arg))
{
// handle the error
}
// empty error means: no error
Any suggestions?
The only way to use that idiom while still keeping your code understandable is if your function returns an object that is convertible to bool in a way that
true
indicates that you want to take the branch andfalse
means that you do not care about it. Anything else is just going to lead to write-only code.One such object which may be relevant happens to be
boost::optional
. Given:You could use the idiom you want in a natural way:
This also has the added benefit where I'd consider an
optional
error message more semantically meaningful than having to check for an empty error message.