On 3/23/23 07:36, Alexander Zhirov wrote:

>      @property auto toString(T)()

The name is misleading because you want types other than string as well.

>      alias toString this;

That should have been a compilation error because 'toString' does not have a known type (because it depends on a template parameter). How can the compiler accept that 'alias this'?

> int myInt       = a;
> float myFloat   = b;

Since you need to spell out 'int' and 'float' in some form anyway, the following would be my choice, which I did use in my code before:

struct MyVal
{
    private string value;

    auto to(T)()
    {
        import std.conv : to;
        return value.to!T;
    }
}

void main() {
    auto a = MyVal("100");
    auto b = MyVal("11.2");

    auto myInt = a.to!int;
    auto myFloat = b.to!float;
}

Should it be an error to convert 'a' to float? If so, the following modules may be helpful:

  https://dlang.org/phobos/std_sumtype.html

  https://dlang.org/phobos/std_variant.html

Ali

Reply via email to