www.digitalmars.com         C & C++   DMDScript  

digitalmars.D - Point before the template

reply "cmplx" <magiisto mail.ru> writes:
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
Jul 16 2013
next sibling parent "Adam D. Ruppe" <destructionator gmail.com> writes:
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 }
Jul 16 2013
prev sibling next sibling parent "cmplx" <magiisto mail.ru> writes:
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'
Jul 16 2013
prev sibling next sibling parent "Adam D. Ruppe" <destructionator gmail.com> writes:
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?
Jul 16 2013
prev sibling parent "cmplx" <magiisto mail.ru> writes:
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
Jul 16 2013