What is the correct way to forward method calls to the struct field?

Philippe Sigaud via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sun Jun 22 09:37:34 PDT 2014


On Sun, Jun 22, 2014 at 5:02 PM, monnoroch via Digitalmars-d-learn
<digitalmars-d-learn at puremagic.com> wrote:
> Thanks a lot!
> There is a problem though: when i pass incorrect parameters to
> such a method, it says, that S has no such field, which is a
> misleading error message.

You can test the mixin with static if, like this:

struct SomeT {
    int foo(double d) { return 0;}
    void bar(double d) { return;}
}

struct S {
  auto opDispatch(string name, Args...)(Args args) {
     static if (is(typeof(mixin("(*iface)." ~ name)(args))))
       return mixin("(*iface)." ~ name)(args);
     else
       pragma(msg, "S." ~ name ~ " cannot be called with arguments of
type " ~ Args.stringof);
    }
    SomeT** iface;
}

void main()
{
  SomeT st;
  SomeT* st_p = &st;
  SomeT** st_p_p = &st_p;
  S s = S(st_p_p);

  s.foo(3.14);
  s.foo("abc");
  s.bar("abc", 3.14);
}


More information about the Digitalmars-d-learn mailing list