Is it possible to override the behavior of a type when used in a conditional expression?
pineapple via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Sat Sep 10 07:29:33 PDT 2016
On Saturday, 10 September 2016 at 14:24:23 UTC, ag0aep6g wrote:
> On 09/10/2016 04:10 PM, pineapple wrote:
>> I've got a struct and it would be very convenient if I could
>> specify
>> what happens when I write `if(value)` - is this possible?
>
> `if (value)` implies a cast to bool. Define opCast!bool and it
> gets called:
>
> ----
> struct S
> {
> bool opCast(T : bool)() { return true; }
> }
> void main()
> {
> S value;
> import std.stdio: writeln;
> if (value) writeln("yup");
> }
> ----
Huh, I could've sworn that some time ago I tried that and it
didn't work. Was this a recent addition to the language?
More information about the Digitalmars-d-learn
mailing list