Figuring out the returntype opDipatch

Ali Çehreli acehreli at yahoo.com
Sat Nov 2 18:56:00 PDT 2013


On 11/02/2013 03:41 PM, TheFlyingFiddle wrote:
> I'm currently working on a IReflectionable interface
>
> Currently the usage is as follows
>
> class Foo : IReflectionable
> {
>    mixin ReflectionImpl;
>
>    void bar(int a) { /* do something */ }
>    int baz(string a) { return a.length; }
>
> }
>
> unittest
> {
>     IReflectionable foo = new Foo();
>
>     alias void delegate(int) bar_t;
>
>     auto bar = foo.funcPtr!(bar_t, "bar"); //Gets a delegate to foo.bar
>     bar(1); //Calls foo.bar(1);
>
>     alias int delegate(string) baz_t;
>     auto baz = foo.funcPtr!(baz_t, "baz");
>     int a = baz("Hello");
> }
>
> Now this works and is all well and good. However i would like to improve
> on the
> syntax a bit.
>
> This is how i would like to call the code.
>
> unittest
> {
>    IReflectionable foo = new FooService();
>
>    foo.bar(1); //Now this becomes foo.opDispatch!("bar", int)(1);
>
>    int a = foo.baz("Hello"); //This does NOT work. Cannot figure out
> returntype
> }
>
> The problem i am faced with is that i need a way to figure out the
> return value of opDispatch by the invokation call.
>
> all the information i need is here
>
> int a = foo.baz("hello");
>
> This gives returntype int.
>
> So is there a way to gain this information in opDspatch? Is it possible
> to do something like this?
>
> auto a = foo.baz!(int)("hello");
>
>
>

Can you provide a little more complete code please. Otherwise, the 
return type is available to typeof:

import std.stdio;

struct S
{
     auto opDispatch(string name, T...)(T parameters)
     {
         writef("S.%s:", name);
         foreach (parameter; parameters) {
             writef(" %s", parameter);
         }
         writeln();

         return parameters[$/2];
     }
}

void main()
{
     auto s = S();

     auto r0 = s.foo(42, 1.5, "hi");
     auto r1 = s.bar("hello", 'a', 100);

     static assert (is (typeof(r0) == double));
     static assert (is (typeof(r1) == char));
}

Ali




More information about the Digitalmars-d-learn mailing list