D - template example question
- Sean Kelly <sean ffwd.cx> Feb 12 2004
- Hauke Duden <H.NS.Duden gmx.net> Feb 12 2004
- "davepermen" <davepermen hotmail.com> Feb 13 2004
- Sam McCall <tunah.d tunah.net> Feb 13 2004
This is in the template docs:
template factorial(int n : 1)
{
enum { factorial = 1 }
}
template factorial(int n)
{
// Note . used to find global template rather than enum
enum { factorial = n* .factorial!(n-1) }
}
void test()
{
printf("%d\n", factorial!(4)); // prints 24
}
Now it seems like a few things are going on here, but I can't find
documentation on any of them. First, using the . prefix seems
equivalent to the :: prefix in C++, is this true? Second, it seems that
it's not an error to declare an enum with the same name as an enclosing
template, but rather that the template can be considered equivalent to
the underlying value. Are there any other instances where this works?
Sean
Feb 12 2004
Sean Kelly wrote:Second, it seems that it's not an error to declare an enum with the same name as an enclosing template, but rather that the template can be considered equivalent to the underlying value. Are there any other instances where this works?
I believe it also works with (at least) classes and structs. Hauke
Feb 12 2004
and functions, too..
template max(T) { T max(T a,T b) { return a > b ? a : b; } }
max!(int)(5,10) returns 10 (with typeof(10) == int, of course:D)
"Hauke Duden" <H.NS.Duden gmx.net> schrieb im Newsbeitrag
news:c0h1vm$2ej0$1 digitaldaemon.com...
Sean Kelly wrote:
Second, it seems that
it's not an error to declare an enum with the same name as an enclosing
template, but rather that the template can be considered equivalent to
the underlying value. Are there any other instances where this works?
I believe it also works with (at least) classes and structs.
Hauke
Feb 13 2004
davepermen wrote:and functions, too.. template max(T) { T max(T a,T b) { return a > b ? a : b; } } max!(int)(5,10) returns 10 (with typeof(10) == int, of course:D)
shortcut templated functions with the restrictions: deduction doesn't work if the template is overloaded with the same number of parameters: void foo(T,int X)(T t) and void foo(T,double X)(T t) would have no type deduction, void foo(T,int[] X)(T t) and void foo(T,int X,int Y)(T t) are ok. For the matching template declaration (by number of args), each type variable must be the type of at least one parameter: void foo(T,U)(T[] t,U u) has no type deduction void foo(T,U)(T a,T[] b,int c,U d) is ok And it could be called with the normal function call syntax, max(5,10). Sam
Feb 13 2004








Sam McCall <tunah.d tunah.net>