2 Templates Issues (possibly bugs)

BCS ao at pathlink.com
Sun Oct 7 09:53:04 PDT 2007


Reply to John,

> Hello there
> 
> I've been experimenting with templates & template mixins, and I have
> some questions & notes, here are they one by one:
> 
> 1- I define a template like this:
> 
> template Template1(T, alias Var, alias Func)
> {
> T abc = Func();		//OK.
> T xyz = Var;		//#1 Error: non-constant expression i1
> //Question 1: Why do I have this error?
> }
> The above error is issued in case I instantiate the template like this
> for ex:
> 
> Template1!(int, i1, Func1).abc = 3;
> Or
> Template1!(int, i1, Func1).xyz = 3;

what is i1 in this case.


> 2- Let's define 2 functions to be used with the previous template
> (template2):
> 
> int Func1()
> {
> return 100;
> }
> int Func2()
> {
> return 200;
> }
> Now the next instantiation fails:
> 
> Template2!(int,Func1,Func2).var1;	//Error: var has no effect in
> expression (var1)


that is correct, referencing the variable var1 but not using it for anything 
has no effect and is disallowed.

The template you defined contains two global variables that are initialized 
with the return from two function that are passed in.

The two issues you mention may be related. What I think is happening is that 
the initializer for a variable must be a constant. Due to compile time function 
evaluation (CTFE) the trivial function you used get converted to there return 
values.

If I had to guess, I'd say that the "i1" from above is a non trivial function 
that can't be run through CTFE. 


> 
> The next one succeeds:
> 
> Template2!(int,Func1,Func2).var1=10;
> 
> Next one succeeds as well (even if the instance is not defined before
> it):
> 
> writefln("var1 = ",Template2!(int,Func1,Func2).var1);	//value is 100
> (as returned by Func1() )
> Template2!(int,Func1,Func2).var1+=30;	//value is now 130
> The question here is why the 1st one fails?
> 
> Also I see a confusion in the expression
> "Template2!(int,Func1,Func2).var1", it's sometimes equivalent to
> variable declaration (as in the previous writefln), and sometimes it's
> equivalent to a symbol (as in the "+=30" statement).. I hope this note
> would be added to the documentation.

as noted above, the expression "Template2!(int,Func1,Func2).var1" is a symbol 
in all cases. it is actually a reference to a global variable declared in 
the template.

I hope that helps, If not, please do ask more questions.

> 
> Regards
> John





More information about the Digitalmars-d mailing list