This reminds me of pattern matching. I'm not sure if the pattern matching proposal allows this, though. Rust would allow something like:
if let Some(x) = some_optional {
...
}
We propose a new variant of the if statement that fuses a condition declaration with an indirection in the true branch. We call it an 'indirect if statement'.
I find it a bit odd that this only works for unary `operator*`. I want this to be more general, but I don't know if there's a good alternative without going for full pattern matching.
I think that it does match the name, as unary `operator*` is the indirection operator. I would think the kinds of types that would benefit from this (raw and smart pointers, optionals, etc.) would all use the indirection operator, though I would certainly like to see a use case for a type that benefits for a different operator. Possibly a function pointer type.
An indirect if statement of the form:
if (DECL : EXPR) X else Y;
is equivalent to:
{
auto&& __c = EXPR;
if (__c) {
DECL = *__c;
X;
} else {
Y; // noteworthy: DECL is not in scope here
}
}
It would sometimes be preferable to forward __c into DECL, but sometimes not. E.g. if EXPR returned an optional<vector<...>> and DECL wanted to be a value and not a reference. I don't know what the right choice is.
I do know that I'd use this if it was in the language.
--
Std-Proposals mailing list
Std-Proposals@lists.isocpp.org
https://lists.isocpp.org/mailman/listinfo.cgi/std-proposals