On Monday, 30 March 2015 at 15:04:20 UTC, Steven Schveighoffer wrote:
On 3/29/15 1:34 PM, IgorStepanov wrote:

1. We should reject types which use opDispatch and alias this at the
same time.

Why? Alias this has no filter. opDispatch can use template constraints. It makes perfect sense to prefer opDispatch, unless it doesn't have a valid match, and then use alias this instead.

For example, if I wanted to wrap a type so I can instrument calls to 'foo', I could do something like this:

struct FooWrapper(T)
{
   T t;
   alias t this;
auto opDispatch(string s, A...)(A args) if(s == "foo") { writeln("calling foo"); return t.foo(args); }
}

Why is this a bad use case?

-Steve

You can split this code to two structs:

struct FooWrapper(T)
{
   struct FooDispatcher
   {
       auto opDispatch(string s, A...)(A args) {
           writeln("calling ", s);
       }
   }
   FooDispatcher d;
   T t;
   alias t this;
   auto foo(string s, A...)(A args)
   {
      writeln("calling foo"); return t.foo(args);
   }
}

FooWrapper!X x;
x.foo(1, 2); //FooWrapper.foo has been called
x.bar(1, 2); //FooWrapper.d.opDispatch has been called
X orig = x; //FooWrepper.t is returned.

===============
Yes, this code is much more tricky, but it work as you wish.
opDispatch + alias this may deliver many problems, if one of those has more high priority then the other. We want to implement alias this maximally strictly, and after that, try to find rules which may be safely relaxed.

Reply via email to