Thread overview
Behavior of std.conv : to with alias this
May 20
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

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 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.

May 21

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 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.

Or it is just an unintended side effect. The current behavior makes these functions useless.