If Statement with Declaration

Steven Schveighoffer via Digitalmars-d digitalmars-d at puremagic.com
Wed Jul 19 08:56:59 PDT 2017


On 7/19/17 11:41 AM, Jack Stouffer wrote:
> On Wednesday, 19 July 2017 at 13:30:56 UTC, sontung wrote:
>> Thoughts on this sort of feature?
> 
> To be frank, I don't think that helping the programmer reduce the line 
> count in their program by one line is worth further complicating the 
> language.

It's 3 lines. One for the extra scope, one for the declaration, and one 
for the closing scope.

Hm... just had an idea:

auto propertyCheck(string condition, T)(T val)
{
     static struct Result {
        T _value;
        opCast(B: bool)() {
           mixin("return _value " ~ condition ~ ";");
        }
        alias _value this;
     }
     return Result(val);
}

if(auto x = someFunc().propertyCheck!" >= 0")
{
    // use x as if it was the result of someFunc()
}

Has some drawbacks, for instance you may want to use the true 
booleanness of whatever T is inside the function.

-Steve


More information about the Digitalmars-d mailing list