Subtyping with alias this

H. S. Teoh hsteoh at quickfur.ath.cx
Mon Aug 17 14:43:27 UTC 2020


On Mon, Aug 17, 2020 at 02:29:47PM +0000, novice3 via Digitalmars-d-learn wrote:
[...]
> ```
> struct IpV4Address
> {
>   private uint ip;
>   alias ip this;
> 
>   string toString()
>   {
>     import std.conv: to;
>     return to!string((ip >>> 24) & 0xFF) ~ "." ~
>            to!string((ip >>> 16) & 0xFF) ~ "." ~
>            to!string((ip >>> 8) & 0xFF) ~ "." ~
>            to!string(ip & 0xFF);
>   }

What you need is to create an overload of toString that takes a
FormatSpec parameter, so that you can decide what should be output for
which format spec.  Something along these lines:

	string toString(W,Char)(W sink, FormatSpec!Char fmt) {
		if (fmt.spec == "s")
			return to!string((ip >>> 24) & 0xFF) ~ "." ~
				to!string((ip >>> 16) & 0xFF) ~ "." ~
				to!string((ip >>> 8) & 0xFF) ~ "." ~
				to!string(ip & 0xFF);
		else
			// Fallback to usual uint-formatting
			return format("%s", ip);
	}


T

-- 
We've all heard that a million monkeys banging on a million typewriters
will eventually reproduce the entire works of Shakespeare.  Now, thanks
to the Internet, we know this is not true. -- Robert Wilensk


More information about the Digitalmars-d-learn mailing list