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

Create successful ePaper yourself

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

4.4. CONCEPTS AND MODELING 97<br />

type parameters. For instance the destructor uses the pointer data with a template type but<br />

the delete function can deduce its type automatically and <strong>for</strong> the null pointer test it does not<br />

matter either.<br />

Template arguments can have default values. Assume, our vector class has in addition to the<br />

value type also two parameters <strong>for</strong> the orientation and location:<br />

template <br />

class vector;<br />

The arguments of a vector can be fully declared:<br />

vector v;<br />

The last argument is equal to the default value and can be omitted:<br />

vector v;<br />

As <strong>for</strong> functions, only the last arguments can be omitted. For instance, if the second argument<br />

is the default and the last one is not we must write them all:<br />

vector w;<br />

If all template arguments are the default values, we can of course omit them all. However the<br />

type is still a template class and the compiler gets confused if we skip the brackets in the type:<br />

vector x; // wrong, it is considered a non−template class<br />

vector y; // looks a bit strange but is correct<br />

Other than the defaults of function arguments, the template defaults can refer to previous<br />

template arguments:<br />

template <br />

class pair;<br />

This is a class <strong>for</strong> two values that might have different types. If they do not we do not want to<br />

declare it twice:<br />

pair p1; // object with an int and float value<br />

pair p2; // object with two int values<br />

The dependency on previous arguments can be more complex than just equality when using<br />

meta-functions that we will introduce in Chapter ??.<br />

TODO: transition to next section<br />

4.4 Concepts and Modeling<br />

In the previous sections one could get the impression that template parameters can be replaced<br />

by any type. This is in fact not entirely true. The programmer of templated classes and functions<br />

makes assumptions about the operations that can be per<strong>for</strong>med on the templated variables. So<br />

it is very important to know which types may correctly be substituted <strong>for</strong> the <strong>for</strong>mal template<br />

parameters, in C ++ lingo which types the template function or class can be instantiated with.<br />

Clearly, accumulate can be instantiated with int or double. Types without addition like a solver

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

Saved successfully!

Ooh no, something went wrong!