/* C++ templates */ #include #include using namespace std; class bigobject {}; template class list { public: T car; list *cdr; list(T a, list *b) {car=a; cdr=b;} int length() { int cx=NULL; for(list i=this;i!=NULL;i=i->cdr) cx++; return cx; // return cx - car; // this will still compile! } // naturally polymorphic T largest() { T max = this->car; for(list i=this->cdr;i!=NULL;i=i->cdr) if (i->car > max) max=i->car; return max / car; // this compiles because C++ doesn't type check generic } }; int main() { list *n = new list(3,NULL); list *m = new list(2.5,NULL); list *p = new list("abc",NULL); //p->largest(); bigobject *big = new bigobject(); bigobject *bigger = new bigobject(); list *b = new list(big,new list(bigger,NULL)); //cout << b->largest(); // only now do you get an error, // when you're writing a template class, how are you sure it won't get // instantiated with a type that it can't handle? // C++ cannot type check template code beyond simple syntax errors return 0; }//main /* C++ templates is just a way for the compiler to create different versions of each class when instantiated. So the above main will actually create 4 copies of the class list. C++ does not try to type check expressions that include variables of generic type at compile time: It cannot check generic types, only the specific types once the template is instantiated. Unlike C# and Java, where you can constrain the range of type variables (where A:C, B extends Comparable). In reality, this is a just a way to automatically copy and paste. Also, naturally polymorphic functions such as the length function is neverthless duplicated, so there isn't really "one function" that works with different types. The most important practical consequence of C++ templates is that if you create a generic template library, say for a data structure on linked lists, the compiler cannot make any guaurantees of your code's type safety for all types that it may be applied to. */