Implicit conversion of struct to bool for if (s) operation ?

John via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Mon Jun 6 08:28:35 PDT 2016


On Monday, 6 June 2016 at 15:23:50 UTC, chmike wrote:
> Hello,
>
> I have a structure with two fields ad defined as
>
> struct Info {
>     this(int value, Category category)
>     {
>         category_ = category;
>         value_ = category ? value : 0;
>     }

       // This converts implicitly to bool.
       T opCast(T : bool)() {
           return category_ !is null;
       }

>     ...
> private:
>     Category category_ = null;
>     int value_ = 0;
> }
>
>
> I would like an implicit conversion of Info to bool that return 
> false if category_ is null so that I can write
>
> Info s = foo();
> if (s) {
>    ...
> }
>
> and where
>
> Info s2;
> assert(!s2);

See the inserted code above.


More information about the Digitalmars-d-learn mailing list