Why no implicit cast operators?
Tommi
tommitissari at hotmail.com
Mon Aug 6 07:48:30 PDT 2012
On Monday, 6 August 2012 at 13:59:30 UTC, jerro wrote:
> Wouldn't you have the exact same problem with implicit casts in
> C++? If you want to use custom operators, you should just
> define those, same as you would in C++. You can even implement
> just some operators and use alias this for functionality that
> you don't want to reimplement, like this:
>
> import std.stdio;
>
> struct A
> {
> int a;
> alias a this;
> auto opOpAssign(string op, T)(T b)
> if(op == "+" && is(typeof(a += T.init)))
> {
> a += b;
> writeln("opOpAssign!\"+\" called.");
> }
> }
>
>
> void main()
> {
> auto a = A(3);
> a += 5u;
> writeln(a);
> writeln(a - 1);
> }
>
> This prints:
>
> opOpAssign!"+" called.
> 8
> 7
Oh... I've had a pretty longstanding misunderstanding then. I
tested something like that a while ago, and didn't manage to get
the custom operator called. Instead the aliased type's default
operator was called. Then I assumed that's how alias this worked.
I must have done something wrong back then, I don't know, can't
find that test code anymore.
More information about the Digitalmars-d
mailing list