T opImplCast(T)() so we can add @disable to it?

Jonathan M Davis newsgroup.d at jmdavisprog.com
Thu May 24 01:39:56 UTC 2018


On Thursday, May 24, 2018 00:30:03 Sjoerd Nijboer via Digitalmars-d wrote:
> While tinkering with some code I eventually found that the
> following didn't do as I expected
>
> import std.conv;
> import std.stdio;
>
> void main()
> {
>      Foo foo = 5;
>      writeln(foo);
> }
>
> struct Foo{
>      int i;
>      alias i this;
>      @disable T opCast(T)();
>      this(int j)
>      {i =j;}
> }
>
> If the cast in the example is implict this code compiles and
> executes.
> If the cast is explicit it doesn't.
> Is there a plan to expose something like 'opImplCast()()' so I
> can @disable it for some types where I absolutely don't want any
> accidental type conversions?
> Shouldn't this just be a feature of D?

If you don't want an implict cast, then why did you declare an alias this?
That's the whole point of alias this. If you want implicit conversions, you
use alias this. If you don't, you don't use alias this. I don't understand
why it would ever make sense to declare an implicit conversion and then
disable it.

Also, if you think that

Foo foo = 5;

is using an implicit cast, you're wrong. That's just calling the
constructor. e.g.

struct S
{
    this(int i)
    {
    }
}

void main()
{
    S s = 42;
}

compiles, but something like

void foo(S s)
{
}

void main()
{
    foo(42);
}

won't.

S s = 42;

is semantically equivalent to

auto s = S(42);

just like it would be in C++.

- Jonathan M Davis



More information about the Digitalmars-d mailing list