Subtyping with alias this

novice3 sorryno at em.ail
Tue Aug 18 05:34:58 UTC 2020


On Monday, 17 August 2020 at 14:43:27 UTC, H. S. Teoh wrote:
> 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:

Sorry, i can't make it works.
I tried ti read format.d, but it too complex for me.

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"

reduced code https://run.dlang.io/is/Kgbhfd

```
import std.format;

struct IpV4Address
{
   private uint ip;
   alias ip this;

   void toString(W,Char)(W sink, FormatSpec!Char fmt)
   {
     sink(fmt.spec);  // ERROR
     //sink("s");       // OK
   }
}
void main()
{
   IpV4Address x;
   assert( format("%s", x) == "s");
}
```
/dlang/dmd-nightly/linux/bin64/../../src/phobos/std/format.d(2243): Error: no property ip for type onlineapp.IpV4Address
/dlang/dmd-nightly/linux/bin64/../../src/phobos/std/format.d(1875): Error: template instance std.format.formatValueImpl!(Appender!string, IpV4Address, char) error instantiating
/dlang/dmd-nightly/linux/bin64/../../src/phobos/std/format.d(576):        instantiated from here: formatValue!(Appender!string, IpV4Address, char)
/dlang/dmd-nightly/linux/bin64/../../src/phobos/std/format.d(6630):        instantiated from here: formattedWrite!(Appender!string, char, IpV4Address)
onlineapp.d(17):        instantiated from here: format!(char, 
IpV4Address)



More information about the Digitalmars-d-learn mailing list