Template docs

Josh Stern josh_usenet at phadd.net
Tue Oct 10 20:54:09 PDT 2006


The "Limitations" section of the language page on templates,
http://www.digitalmars.com/d/template.html  is confusing.   In 
particular, the sentence and example "Templates cannot be used 
to add non-static members or functions to classes. For example:

*************************************************
class Foo
{
    template TBar(T)
    {
	T xx;			// Error
	int func(T) { ... }	// Error

	static T yy;				// Ok
	static int func(T t, int y) { ... } 	// Ok

}

*******************************************************************

What is the "Error" in the code above?   Are the docs just out of
date?  The following apparently equivalent code, exercising template
member functions and data, declared within the enclosing class and 
outside it, seems to compile and run fine:

********************************************************************
import std.stdio;

class OBar(T) {
  T xx;
  
  this(T v) { xx = v; }
  
  double func(T t) { return t*5; }
  
}


class BadFoo {

  class TBar(T) {
    T xx;
    
    this(T v) { xx = v; }
    
    double func(T t) { return t*5; }
    
  }



  this() { 
    d_obar = new OBar!(double)(7.69); 
    d_tbar = new TBar!(double)(8.1);
  }

  OBar!(double) d_obar;
  TBar!(double) d_tbar;

  double func(T)(T t) { return d_tbar.func(t); }
}



class Foo(T) {
  this(T t) { d_foo=t; }

  T val() { return d_foo; }

  T d_foo;
}

class Test1 {

  this(double d) { d_m = d; d_d_foo = new Foo!(double)(3.14159);  }

  double prod(T)(T t) { return t*d_d_foo.val(); }
  
  double d_m;



  Foo!(double) d_d_foo;


}


void main() {


  Test1 t1 = new Test1(3.14);

  BadFoo bf = new BadFoo;
  

  writefln(t1.prod(5));
  writefln(bf.func(5));
}

***********************************************************************



More information about the Digitalmars-d-learn mailing list