www.digitalmars.com         C & C++   DMDScript  

digitalmars.D - Behavior of std.conv : to with alias this

reply =?UTF-8?B?Sm/Do28gTG91cmVuw6dv?= <jlourenco5691 gmail.com> writes:
```d
import std;

void main()
{
     struct Foo {
         string s = "string";
         alias s this;

         string toString() { return s.format!"Foo(%s)"; }
     }
     Foo().to!string.writeln;   // string
     Foo().format!"%s".writeln; // Foo(string)


     struct Bar {
         int s = 3;
         alias s this;

         T opCast(T)() { return 43; }
     }
     Bar().to!int.writeln;      // 3
     (cast(int) Bar()).writeln; // 43


     struct Baz {
         T opCast(T)() { return 43; }
     }
     Bar().to!int.writeln;      // 43
     (cast(int) Bar()).writeln; // 43
}
```

Is this the intended behavior of `std.conv : to`?
Shouldn't it only fallback to the `alias this` if **none** of 
those work?
May 20
parent reply Paul Backus <snarwin gmail.com> writes:
On Thursday, 20 May 2021 at 16:19:02 UTC, João Lourenço wrote:
 Is this the intended behavior of `std.conv : to`?
 Shouldn't it only fallback to the `alias this` if **none** of 
 those work?
The [documentation][1] of `std.conv.to` doesn't mention anything about implicit conversions or `alias this`, so at the very least, this is a bug in the documentation. [1]: http://phobos.dpldocs.info/std.conv.to.html
May 20
parent =?UTF-8?B?Sm/Do28gTG91cmVuw6dv?= <jlourenco5691 gmail.com> writes:
On Thursday, 20 May 2021 at 18:27:02 UTC, Paul Backus wrote:
 On Thursday, 20 May 2021 at 16:19:02 UTC, João Lourenço wrote:
 Is this the intended behavior of `std.conv : to`?
 Shouldn't it only fallback to the `alias this` if **none** of 
 those work?
The [documentation][1] of `std.conv.to` doesn't mention anything about implicit conversions or `alias this`, so at the very least, this is a bug in the documentation. [1]: http://phobos.dpldocs.info/std.conv.to.html
Or it is just an unintended side effect. The current behavior makes these functions useless.
May 21