Q: What do you mean by templates?
Templates are a feature of the C++ programming language that allow functions and classes to operate with generic types. This allows a function or class to work on many different data types without being rewritten for each one.
Most programmers who use templates use them to write data structures like lists and other containers. Templates are a natural match for lists (and container classes in general) because they not only let programmers write one List implementation rather than many different List kinds for all the different types of values that lists will need to store, but also let them write down statically-checkable rules like "this particular list must contain ints only." For example, In C++, you could write a simple linked-list as follows:
template
class ListNode {
public:
ListNode(T it, ListNode* next) {
this->it = it;
this->next = next;
}
T getItem() { return it; }
ListNode* nextNode() { return next; }
private:
T it;
ListNode* next;
};
When the compiler sees this code, it remembers the definition but emits no assembly instructions. Later, when it sees a use of the template instantiated with a particular type (say, int) that it hasn't seen before, it generates a fresh code fragment by replacing T with int everywhere in the body of the class definition and changing the class name to be unique, and then rewrites the usage to refer to the newly-generated code. So the code would allow you to write type-safe lists of any type:
// fine
ListNode* il = new ListNode(2, new ListNode(4, NULL));
// also fine
ListNode* sl = new ListNode("hi", new ListNode("bye", NULL));
// type error
ListNode* il2 = new ListNode(3, new ListNode("hi", NULL));
// fine
int i = il->getItem();
// also fine
string s = sl->getItem();
// type error
string s2 = il->getItem();
There are two kinds of templates: function templates and class templates.
|