Given the following linked list class which works for integers, convert it
into a class template:
class LinkedList; class ListElement { int datum; ListElement* next; ListElement (int const&, ListElement*); friend LinkedList; }; class LinkedList { ListElement* head; public: LinkedList (); ~LinkedList (); bool IsEmpty () const; int const& First () const; int const& Last () const; void Prepend (int const&); void Append (int const&); void Extract (int const&); void Print (); };
A function or class template is a framework. The compiler must generate the details of the functions or classes through a process know as instantiating.
Through this process, actual types (or classes) are substituted in for "dummy" or placeholder types. In other words, the compiler generates different versions based on the specified type (or class).
Instantiation works a little different for classes than for functions.Given the following function prototype and class outline:
template <class type> myfunc(type a, type b);
template <class type> class myarray { type a[10]; public: myarray() { for (int i; i<10; i++) a[i] } }Specify how to instantiate the following:
float x=3.12;You may get a warning:
warning C4305: 'initializing' : truncation from 'double' to 'float'
|
|
|