Thread overview
templates in functions
Jul 27, 2007
BCS
Jul 30, 2007
BCS
July 27, 2007
Why can't templates be put into functions like this

|void foo()
|{
|  template Bar(int i){int Bar;}
|
|  Bar!(5) = 7;
|  Bar!(12) = 3;
|  writef("%s, %s\n", Bar!(5), Bar!(12));// prints "7, 3"
|}

this would be vary useful in templated code where a number of variables need to be declared outside of the scope where they will be used

|void foo(A...)()
|{
|  template Bar(int i){int Bar = 0;}
|
|  while(cond())
|  {
|    foreach(i, v; A)
|      Bar!(i) = A(Bar!(i)); // values not reset
|  }
|}

(in this case, trivial work around exist but I have run into cases where it is much harder to work out a solution)

I don't think that this would cause problems because the template could only be used inside the function and therefor by the end of the semantic pass all instances of the template would be known.

for this case a short hand syntax might even be worthwhile, but I can't think what it would be.

int Bar(int i) = 0;  // looks like a fn decoration
int(int i) Bar = 0;  // ??
int template(int i) Bar = 0; // just looks odd
template(int i) int Bar = 0; // template ID( args ) [ decoration | '{' decorationList '}' ]


July 28, 2007
BCS wrote:

> Why can't templates be put into functions like this
> 
> |void foo()
> |{
> |  template Bar(int i){int Bar;}
> |
> |  Bar!(5) = 7;
> |  Bar!(12) = 3;
> |  writef("%s, %s\n", Bar!(5), Bar!(12));// prints "7, 3"
> |}
> 
> this would be vary useful in templated code where a number of variables need to be declared outside of the scope where they will be used

Templates seem to be tightly anchored to the module level at the moment so this isn't possible. But what you're doing here is pretty straightforward extension to the current syntax.

I have a suggestion. Why not collect a list of necessary metaprogramming use cases / constructs (also those that are not possible today) and model a new system that covers them in a clean way (in case you're not doing something like that already <g>). Although it may be by pure luck that many of the current constructs are fixable incrementally at least to some extend. C++ templates are an abomination of the complete metaprogramming frameworks that languages like Lisp possessed. Currently implementation difficulties seem to drive the language evolution, which is quite unfortunate in my opinion. :-/
July 30, 2007
Reply to Jari-Matti Mäkelä,

> I have a suggestion. Why not collect a list of necessary
> metaprogramming use
> cases / constructs (also those that are not possible today) and model
> a new
> system that covers them in a clean way (in case you're not doing
> something
> like that already <g>). 

Should I add that to my talk at the conference? <G>