Smalltalk and Java have a single class heirarchy. C++ does not. Multiple inheritence presents a problem in using containers. In Java, you can create a function that takes an arguement of type object. This will take any type and process it. The discussion of virtual types from before shows how you can take a formal argument of a base type and pass in an actual parameter of a derived type and use virtual functions to manipulate it.
In a sense, you could write macros to generate the specific code needed to to implement a generic code for a given type. For example,
void myprint(char c) { printf("character is %c\n",c); } // myprint
void myprint(int i) { printf("character is %d\n",i); } // myprint
void myprint($mytype$ m) { printf("character is %$myformat$\n",m); } // myprintBefore the code is compiled, we process the place holders to make the right types.
A typical integer stack (with no error checking
class stack { public: stack(){top=-1;}; void push(int i) { s[++top]=i;}; int pop() {return(s[top--]);}; private: int s[100]; int top; } // stackA template stack
template <class SOME_TYPE> class stack { public: stack(){top=-1;}; void push(SOME_TYPE i) { s[++top]=i;}; int pop() {return(s[top--]);}; SOME_TYPE top_of(); private: SOME_TYPE s[100]; int top; } // stackT use this, we declare a stack of a given type:
stack<char> char_stack; stack<int> int_stack;To get the types right, if a member function is not defined inline, it looks like:
template<class SOME_TYPE> SOME_TYPE stack<SOME_TYPE>::top_of() { return(s[top];}Inline, this would have been:
SOME_TYPE top_of() {return(s[top]);};
template<class SOME_TYPE> void copy(SOME_TYPE a,SOME_TYPE b) { a=b; }//copyThis can be done with multiple types as well.
template<class SOME_TYPE1,class SOME_TYPE2> void copy(SOME_TYPE1 a,SOME_TYPE2 b) { a=b; }//copyThis needs to make sense. If not, write an assignment operator so it does make sense. You may need to make special case versions. For example, the copy above won't work for arrays. You need to write a copy() that contains those types specificaly, not generically. This will take precedence over template.
There are separate static members for each instantiation. This is expected. It would not mean anything if the static member was an int even when the template was a float.