Thread overview
Implicit conversion to templatized type
Nov 06, 2020
Andrey Zherikov
Nov 06, 2020
Paul Backus
Nov 06, 2020
H. S. Teoh
November 06, 2020
There is a way to implicitly convert non-template user type, for example:
--------------------
struct S2
{
    @property S1 s1() { return S1(); }
    alias s1 this;
}

struct S1 {}

S1 f() { return S2(); }   // implicit conversion from S2 to S1
--------------------

But how can I achieve the same result if S1 is a template "struct S1(T) {}" and S2 should be convertible to S1!T with any T?

Also why neither "opCast"
    struct S2 { S1 opCast(T)() const if(is(T == S1)) { return S1(); } }
nor suitable ctor
    struct S1 { this(const S2 s){} }
are used for implicit conversion?

November 06, 2020
On Friday, 6 November 2020 at 15:01:21 UTC, Andrey Zherikov wrote:
>
> But how can I achieve the same result if S1 is a template "struct S1(T) {}" and S2 should be convertible to S1!T with any T?
>
> Also why neither "opCast"
>     struct S2 { S1 opCast(T)() const if(is(T == S1)) { return S1(); } }
> nor suitable ctor
>     struct S1 { this(const S2 s){} }
> are used for implicit conversion?

This is impossible by design. User-defined implicit conversions are one of the most error-prone features of C++, and have been deliberately excluded from D, with the exception of `alias this`.
November 06, 2020
On Fri, Nov 06, 2020 at 03:36:46PM +0000, Paul Backus via Digitalmars-d-learn wrote: [...]
> User-defined implicit conversions are one of the most error-prone features of C++, and have been deliberately excluded from D, with the exception of `alias this`.

And Walter is already expressing regret at allowing `alias this`.  I used to love `alias this`, and still use it in many of my projects, but over time, I'm also starting to agree with Walter that it was a mistake. Implicit conversions are generally not a good idea, except in very narrow, well-defined cases. They are convenient, but lead to problems in long-term maintenance.


T

-- 
People who are more than casually interested in computers should have at least some idea of what the underlying hardware is like. Otherwise the programs they write will be pretty weird. -- D. Knuth