25.09.2017 Views

cpp_tutorial

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

34. TEMPLATES<br />

C++<br />

Templates are the foundation of generic programming, which involves writing<br />

code in a way that is independent of any particular type.<br />

A template is a blueprint or formula for creating a generic class or a function.<br />

The library containers like iterators and algorithms are examples of generic<br />

programming and have been developed using template concept.<br />

There is a single definition of each container, such as vector, but we can define<br />

many different kinds of vectors for example, vector or vector .<br />

You can use templates to define functions as well as classes, let us see how<br />

they work:<br />

Function Template<br />

The general form of a template function definition is shown here:<br />

template ret-type func-name(parameter list)<br />

{<br />

}<br />

// body of function<br />

Here, type is a placeholder name for a data type used by the function. This<br />

name can be used within the function definition.<br />

The following is the example of a function template that returns the maximum of<br />

two values:<br />

#include <br />

#include <br />

using namespace std;<br />

template <br />

inline T const& Max (T const& a, T const& b)<br />

{<br />

return a < b ? b:a;<br />

}<br />

int main ()<br />

{<br />

258

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!