Subtyping with alias this

H. S. Teoh hsteoh at quickfur.ath.cx
Tue Aug 18 05:54:16 UTC 2020


On Tue, Aug 18, 2020 at 05:34:58AM +0000, novice3 via Digitalmars-d-learn wrote:
[...]
> The problem is:
> if i use fmt.spec in overloaded toString(),
> when i get error "phobos/std/format.d(2243): Error: no property ip for
> type onlineapp.IpV4Address"

Here's a working example:

---------------------------------------------
import std;

struct IpV4Address
{
	private uint ip;
	alias ip this;

	void toString(W,Char)(W sink, FormatSpec!Char fmt)
	{
		if (fmt.spec == 's') {
			// Deal with %s here
			sink.formattedWrite("%d.%d.%d.%d",
				(ip >> 24) & 0xFF, (ip >> 16) & 0xFF,
				(ip >> 8) & 0xFF, ip & 0xFF);
		} else {
			// Everything else
			formatValue(sink, this.ip, fmt);
		}
	}

	// This unittest is to workaround the sillyness that if toString
	// doesn't compile, std.format pretends it doesn't exist and/or
	// the compiler swallows the real error and substitutes it with
	// an irrelevant error that has nothing to do with the real
	// problem.
	unittest
	{
		IpV4Address ip;
		auto app = appender!string;
		ip.toString(app, FormatSpec!char.init);
	}
}

unittest
{
	auto ip = IpV4Address(0x01020304);
	writefln("%s", ip);
	writefln("%x", ip);
	writefln("%d", ip);
}
---------------------------------------------


T

-- 
No! I'm not in denial!


More information about the Digitalmars-d-learn mailing list