How to check if variable of some type can be of null value?

JG JG at somewhere.com
Sat Jul 24 20:10:37 UTC 2021


On Saturday, 24 July 2021 at 19:39:02 UTC, Alexey wrote:
> On Saturday, 24 July 2021 at 18:10:07 UTC, Alexey wrote:
>> I've tried to use ```typeof(t) is cast(t)null```, but compiler 
>> exits with error and so this can't be used for checking this 
>> issue.
>>
>> The goal I with to achieve by this check - is to use template 
>> and to assign value to variable basing on it's ability to 
>> accept null as a value.
>>
>
> currently I ended up using ```__traits(compiles, 
> cast(T1)null)``` for this check. but don't know is this really 
> semantically correct.

There are probably better ways. However, this seems to work:
```d
import std;
enum canBeSetToNull(T) = __traits(compiles,(T.init is null));

interface I1
{
}

class C1 : I1
{
}

struct S1
{
}

     struct S2
     {
         int a=1;
     }

     void main()
     {
         auto c1 = new C1;

         I1 i1 = c1;

         auto s1 = S1();
         auto s2 = S2();

         static assert(canBeSetToNull!(typeof(c1)));
         static assert(canBeSetToNull!(typeof(i1)));
         static assert(!canBeSetToNull!(typeof(s1)));
         static assert(!canBeSetToNull!(typeof(s2)));
         static assert(!canBeSetToNull!(int));
         static assert(canBeSetToNull!(int*));

}```


More information about the Digitalmars-d-learn mailing list