Implicit conversion from null in custom type

Meta via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Thu May 28 06:46:50 PDT 2015


On Thursday, 28 May 2015 at 11:19:39 UTC, Vladimir Panteleev 
wrote:
> I'm trying to write a type which (to some extent) emulates 
> built-in AAs.
>
> One thing I'm having trouble with is null function parameters:
>
> void fun(S s) {}
> void main() { fun(null); }
>
> How can S implement implicit conversion from null?
>
> I've already tried "alias this" and a constructor taking 
> typeof(null).

What about defining a static `nil` value for S?

import std.stdio;

struct S
{
	static S nil = S(0);
		
	int n;
}

void fun(S s)
{
     if (s == S.nil)
         writeln("null S");
     else
         writeln("Non-null S");
}

void main()
{
     fun(S.nil);
}


More information about the Digitalmars-d-learn mailing list