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.

4.6. TEMPLATE SPECIALIZATION 101<br />

an appropriate technique to achieve polymorphism.<br />

4.6 Template Specialization<br />

Although one of the advantages of a generic implementation is that the same code can be used<br />

<strong>for</strong> all objects that satisfy the corresponding concept, this is not always the best approach.<br />

Sometimes the same behavior can be implemented more efficiently <strong>for</strong> a specific type. In<br />

principle, one can even implement a different behaviour <strong>for</strong> a specific type but this is not<br />

advisable in general because the program becomes much more complicated to understand and<br />

using the specialized classes can require a whole chain of further specialization (bearing the<br />

danger of errors when imcompletely realized). C ++ provides an enormous flexibility and the<br />

programmer is in charge to use this flexibility responsibly and <strong>for</strong> being consistent to himself.<br />

4.6.1 Specializing a Class <strong>for</strong> One Type<br />

In the following, we want to specialize our vector example from page 96 <strong>for</strong> bool. Our goal is<br />

to save memory by packing 8 bools into one byte. Let us start with the class definition:<br />

template <br />

class vector<br />

{<br />

// ..<br />

};<br />

Although our specialized class is not type-parametric, we still need the template key word and<br />

the empty triangle brackets. After the class the complete type list must be given. This syntax<br />

looks a bit cumbersome in this context but makes more sense <strong>for</strong> multiple template arguments<br />

where only some are specialized. For instance, if we had some container with 3 arguments and<br />

specialize the second one:<br />

template <br />

class some container<br />

{<br />

// ..<br />

};<br />

Back to our boolean vector class. In the class we define a default constructor <strong>for</strong> empty vectors,<br />

a constructor <strong>for</strong> vectors of size n and a destructor. In the size of the array, we have to pay<br />

some attention if the vector size is not disible by 8 because the integer division simply cuts off<br />

the remainder.<br />

template <br />

class vector<br />

{<br />

public:<br />

explicit vector(int size)<br />

: my size(size), data(new unsigned char[(my size + 7) / 8] )<br />

{}<br />

vector() : my size(0), data(0) {}

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

Saved successfully!

Ooh no, something went wrong!