Error in template instantiation from D-Cookbook example
Meta
jared771 at gmail.com
Fri Feb 9 21:58:51 UTC 2018
On Friday, 9 February 2018 at 21:31:29 UTC, ShadoLight wrote:
> writeln(parse(code)); // to aid with debugging
> writeln(convertToD(parse(code))); // debugging aid
> ..to..
> writeln(parse(code)[]); // to aid with debugging
> writeln(convertToD(parse(code))[]); // debugging aid
The problem becomes apparent once you uncomment one of these and
paste the offending string ("5 5 + 3 - 2 * 1 + 3 /") in.
`writeln(convertToD(parse("5 5 + 3 - 2 * 1 + 3 /"))[]);` prints
the following:
push(5);
push(5);
push(call!+(pop(), pop()));
push(3);
push(call!-(pop(), pop()));
push(2);
push(call!*(pop(), pop()));
push(1);
push(call!+(pop(), pop()));
push(3);
push(call!/(pop(), pop()));
If you look at the definition of call:
int call(string op)(int a, int b) {
return mixin("b"~op~"a");
}
So it takes a string as its sole template argument. The problem
is that the code in convertToD forgot to add the quotes around
the operators that are supposed to be passed as strings to call.
If you modify line 14 from the example you pasted to add these
quotes to the mixin string, it works:
code ~= "push(call!"~piece~"(pop(), pop()));\n";
becomes
code ~= "push(call!\""~piece~"\"(pop(), pop()));\n";
Running the modified code, it prints:
push(5);
push(5);
push(call!"+"(pop(), pop()));
push(3);
push(call!"-"(pop(), pop()));
push(2);
push(call!"*"(pop(), pop()));
push(1);
push(call!"+"(pop(), pop()));
push(3);
push(call!"/"(pop(), pop()));
And `runDslCode!"5 5 + 3 - 2 * 1 + 3 /"();` prints `[5]`.
More information about the Digitalmars-d-learn
mailing list