How to check if variable of some type can be of null value?
JG
JG at somewhere.com
Sat Jul 24 20:12:11 UTC 2021
On Saturday, 24 July 2021 at 20:10:37 UTC, JG wrote:
> On Saturday, 24 July 2021 at 19:39:02 UTC, Alexey wrote:
>> [...]
>
> 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*));
>
> }```
Sorry, I see that is basically what you had.
More information about the Digitalmars-d-learn
mailing list