Templates
Advantages of templates:
- Code reuse
- Allows container classes (e.g. lists, arrays, etc.) to be simply defined without loss of static type checking or run-time efficiency.
- Allows definition of generic functions (e.g., sort) to be defined once for a family of types
Function template and template function:
- Function templates are used to implement an entire range of related(overloaded) functions.
- When the actual parameter is substituted in the template the process is called instantiating the function template and each instantiated version is called a template function. i.e. template function is a specific instance of function template.
Class templates and template class:
- Class templates are used to implement an entire range of related classes.
- Template class is the instantiation with the type argument.
Auto_ptr:
- Auto_ptr is a template class and is initialized with a pointer and can be derefenced in the way a pointer can.
- Auto_ptr supports resource acquisition is initialization technique.
- Auto_ptr has ownership semantics or destructive copy semantics: When an auto_ptr is copied into another, the source no longer points to anything.
- Copying a auto_ptr modifies it – a const auto_ptr cannot be copied.
- The purpose of the auto_ptr scheme is that dynamically allocated objects are properly destroyed in all circumstances i.e. the object’s destructor is properly executed.
- Template specification of auto_ptr:
template
class auto_ptr
{
public:
typedef T element_type;
explicit auto_ptr(T *p = 0) throw();
auto_ptr(const auto_ptr& rhs) throw();
auto_ptr& operator=(auto_ptr& rhs) throw();
~auto_ptr();
T& operator*() const throw();
T *operator->() const throw();
T *get() const throw();
T *release() const throw();
};
Example:
#include
#include
using namespace std;
class X
{
public:
X() { cout << “X::X()\n” ;}
~X() { cout << “X::~X()\n” ;}
void f() { cout << “X::f()\n”; }
};
int main()
{
auto_ptr p1(new X), p2;
p2 = p1; // ownership transfer
p2->f();
X *ptr = p2.get();
ptr ->f();
return 0;
}
Result:
X::X()
X::f()
X::f()
X::~X() (Destructor called when scope ends)