shortcut for dynamic dispatch and operators

KennyTM~ kennytm at gmail.com
Tue Dec 1 08:18:19 PST 2009


On Dec 1, 09 22:30, Steven Schveighoffer 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.
>
> -Steve

Alternative suggestion:

Make "x in y" returns a bool and works for arrays. Then you can write

int opBinary(string s)(int rhs) if (s in ["+", "-", "*", "/", "^", "|", 
"&"]) { ... }




More information about the Digitalmars-d mailing list