If Statement with Declaration
Steven Schveighoffer via Digitalmars-d
digitalmars-d at puremagic.com
Fri Nov 4 09:15:21 PDT 2016
On 11/4/16 11:27 AM, Jerry wrote:
> On Friday, 4 November 2016 at 14:10:51 UTC, Steven Schveighoffer wrote:
>> Hm... what about something like:
>>
>> struct BoolCond(T, string cond)
>> {
>> T val;
>> bool opCast(B)() if(is(B == bool))
>> {
>> return mixin("val " ~ cond);
>> }
>> }
>>
>> auto boolcond(string cond, T)(T val)
>> {
>> return BoolCond!(T, cond)(val);
>> }
>>
>> if(auto i = someFunc.boolcond!(">= 0"))
>> {
>> ... // use i
>> }
>>
>
> Well that's just a basic case, what if you want more than one condition.
> Using "&&" for example, or a condition along with another value that's
> in the scope.
It's just a strawman type, I'm sure there's ways to handle these things,
I just didn't put a lot of effort into all the cases.
But really it's just syntax to separate the bool check from the value
itself. You can get more elaborate if you want with the comparison. The
difficult thing is having a type that you use normally, but that when
you use in an if statement, it gives what you want. And declaring that
type in the if clause itself (which is allowed in restricted circumstances).
This also isn't exactly ideal for things like int, as if(i) would now be
unexpected.
> Then you need another work around for something like this:
>
> if(int value; auto i = someFunc(&value))
> {
> // ...
> }
I thought you could only declare variables in the first clause?
In any case, I think Stefan really has the best answer:
{int value; if(auto i = someFunc(&value))
{
// ...
}}
Sure, it doesn't look great. But my expectation is that your proposal
doesn't pull enough weight to be integrated into the language. There are
enough ways to solve this problem that don't involve language changes.
-Steve
More information about the Digitalmars-d
mailing list