shortcut for dynamic dispatch and operators

Bill Baxter wbaxter at gmail.com
Tue Dec 1 08:24:17 PST 2009


On Tue, Dec 1, 2009 at 6:30 AM, Steven Schveighoffer
<schveiguy at yahoo.com> wrote:
> An idea I just had when thinking about how ugly opDispatch and opBinary
> operators will be if we get those was, wouldn't it be cool if the compiler
> could translate:
>
> myTemplateMethod("abc" || "def")() if(condition) {}
>
> to
>
> myTemplateMethod(string __x)() if((__x == "abc" || __x == "def") &&
> condition) {}
>
> It makes dispatch based on compile-time strings much more palatable, for
> example:
>
> opDispatch("foo" || "bar")() {...}
> opBinary("+" || "-" || "*")(int rhs) {...}
>
> instead of:
>
> opDispatch(string fn)() if(fn == "foo" || fn == "bar") {...}
> opBinary(string op)() if(op == "+" || op == "-" || op == "*")(int rhs) {...}
>
> In fact, it can be generalized to any type which has literals:
>
> factorial(int x)(){ return factorial!(x-1)() * x;}
> factorial(1)() { return 1;}
>
> What I don't know is if the || works in all cases -- because something like
> true || false is a valid expression.  Maybe someone can come up with a
> better way.

The closest thing is the specialization syntax:

    factorial(int x : 1)() { return 1;}

The main problem with your suggestion is that for most practical uses
you actually need to know what the parameter was, not just that it was
either "foo" or "bar".  So you need to put a symbol somewhere in that
signature to bind the actual value to.

But I agree, some syntax like
   opDispatch(x : "foo" || "bar")() {  /* use x */ ...}

would look much nicer.  And it's pretty close to current
specialization syntax for values.  The type "string" can be
auto-deduced from the stuff after the colon.  But there are more
conditions that you'd like to test than just "||".  I guess I'd prefer
to just be able to move a whole if clause to after a colon.

    void opDispatch(fn : fn == "foo" || fn == "bar")(Variant arg...) {}

--bb



More information about the Digitalmars-d mailing list