How to use a non-static objects in string `mixin`?

Dukc ajieskola at
Mon Aug 29 19:39:01 UTC 2022

On Saturday, 27 August 2022 at 13:20:13 UTC, hype_editor wrote:
> I need to use function `eval` sometimes, but compiler throws an 
> error: `Error: variable `firstOperand` cannot be read at 
> compile time`.

You're probably misunderstanding `mixin`. It does not work like 
an eval function at Lisp or
  JavaScript or such. Instead, it evaluates it's contents at 
compile time, meaning that you can only use compile-time data in 
it, `enum` variables and template arguments for example.

Because the operator is not known at compile time, this means you 
need something else. Switch statement Paul Backus suggested is 
one option. You could alternatively try an associative array that 
maps the operators to the respective functions, something like 
enum opMap =
[ "+": (double a, double b) => a+b,
   "-": (double a, double b) => a-b,

//in the eval function
return opMap[operator](firstOperand, secondOperand);

More information about the Digitalmars-d-learn mailing list