03.12.2012 Views

C++ for Scientists - Technische Universität Dresden

C++ for Scientists - Technische Universität Dresden

C++ for Scientists - Technische Universität Dresden

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Generic programming<br />

Chapter 4<br />

In this chapter we will explain the use of templates in C ++ to create generic functions and<br />

classes. We will also discuss metaprogramming and the Standard Template Library.<br />

4.1 Templates<br />

Templates are a feature of the C ++ programming language that create functions and classes<br />

that operate with generic types — also called parametric types. As a result, a function or class<br />

can work with many different data types without being manually rewritten <strong>for</strong> each one.<br />

A template parameter is a special kind of parameter that can be used to pass a type as an<br />

argument: just like regular function parameters can be used to pass values to a function,<br />

template parameters allow to pass also types to a function or a class. These generic functions<br />

can use these parameters as if they were any other regular type.<br />

4.2 Generic functions<br />

Generic functions — also called function templates — are in some sort generalizations of overloaded<br />

functions.<br />

Suppose we want to write the function max(x,y) where x and y are variables or expressions of<br />

some type. Using overloading, we can easily do this as follows:<br />

int inline max (int a, int b)<br />

{<br />

if (a > b)<br />

return a;<br />

else<br />

return b;<br />

}<br />

double inline max (double a, double b)<br />

{<br />

if (a > b)<br />

return a;<br />

89

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

Saved successfully!

Ooh no, something went wrong!