Template variable not reach at compile

rikki cattermole rikki at cattermole.co.nz
Sat Jul 21 12:21:08 UTC 2018


On 22/07/2018 12:15 AM, Greatsam4sure wrote:
> auto arithmetic(T, V, U)(T a,  V b,  U op){
>     return mixin("a"~op~"b");
> }
> 
> //call like this
> arithmetic(1.5,2.5,"op");
> 
> 
> Compiler says the variable op is not reach at compile time.  So how can 
> the varible a and b be reach at compile time and op is not reach. I will 
> appreciate any help. I have also use a static if but the same complain.  
> Just a newbie in D

Simple, it was never requested to be reached.

The correct code is:

auto arithmetic(string op, T, V)(T a, V b) {
	return mixin("a" ~ op ~ "b");
}

arithmetic!("op")(1.5, 2.5);

D is not dynamic, if you need access to compile time features like 
string mixin, you must pass them via the template parameters. You can't 
use regular old variables to do this, as the code hasn't even been 
generated yet.


More information about the Digitalmars-d-learn mailing list