Thread overview
Point before the template
Jul 16, 2013
cmplx
Jul 16, 2013
Adam D. Ruppe
Jul 16, 2013
cmplx
Jul 16, 2013
Adam D. Ruppe
Jul 16, 2013
cmplx
July 16, 2013
Example of recursive templates in http://dlang.org/template-comparison.html

template factorial(int n) {
       const factorial = n * factorial!(n-1);
 }
template factorial(int n : 1) {
         const factorial = 1;
 }

void test() {
	writefln("%d", factorial!(4)); // prints 24
}

But I was wrong when I tried this example and put point before the factorial. But it still worked. why?

template factorial(int n) {
       const factorial = n * .factorial!(n-1);//<------
 }
template factorial(int n : 1) {
         const factorial = 1;
 }
void test() {
	writefln("%d", factorial!(4)); // prints 24
}

I`m using DMD 2.063
July 16, 2013
On Tuesday, 16 July 2013 at 21:03:07 UTC, cmplx wrote:
> But I was wrong when I tried this example and put point before the factorial. But it still worked. why?

In D, .name means "look up name in the global scope". Since factorial is in the global scope, it found it successfully and everything worked.

The place this would be useful is something like this:


int a = 10;

void foo() {
   int a = 20;
   writeln(a); // 20
   writeln(.a); // 10 - the dot tells it to use the global instead of the local
}
July 16, 2013
On Tuesday, 16 July 2013 at 21:07:31 UTC, Adam D. Ruppe wrote:
> On Tuesday, 16 July 2013 at 21:03:07 UTC, cmplx wrote:
>> But I was wrong when I tried this example and put point before the factorial. But it still worked. why?
>
> In D, .name means "look up name in the global scope". Since factorial is in the global scope, it found it successfully and everything worked.
>
> The place this would be useful is something like this:
>
>
> int a = 10;
>
> void foo() {
>    int a = 20;
>    writeln(a); // 20
>    writeln(.a); // 10 - the dot tells it to use the global instead of the local
> }

Compile error:
Error: undefined identifier 'a'
July 16, 2013
On Tuesday, 16 July 2013 at 22:12:36 UTC, cmplx wrote:

> Compile error:
> Error: undefined identifier 'a'

Are you sure the int a = 10; was copied outside the function too?
July 16, 2013
On Tuesday, 16 July 2013 at 22:17:58 UTC, Adam D. Ruppe wrote:
> On Tuesday, 16 July 2013 at 22:12:36 UTC, cmplx wrote:
>
>> Compile error:
>> Error: undefined identifier 'a'
>
> Are you sure the int a = 10; was copied outside the function too?

yes, you are right, 'a' has been initialised in the 'main' and therefore was a mistake
thank you