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.6. TEMPLATE SPECIALIZATION 103<br />

class vector bool proxy<br />

{<br />

vector bool proxy& operator=(bool b)<br />

{<br />

if (b)<br />

byte|= mask;<br />

else<br />

byte&= ∼mask;<br />

return ∗this;<br />

}<br />

};<br />

If our argument is true we ‘or’ it with the mask, i.e. on the considered position the one bit in<br />

the mask turns on the bit in the byte reference and in all other positions the zero bits in the<br />

mask leave the according positions unchanged. Reversely with a false argument, we first invert<br />

the mask and ‘and’ it with the byte reference so that the mask’s zero bit on the active position<br />

turns the bit off and on all other positions the ‘and’ with one bits conserves the old bit values. 8<br />

4.6.2 Specializing a Function to a Specific Type<br />

Functions can be specialized in the same manner as classes. Assume we have a generic function<br />

that computes the power x y and want specialize this one:<br />

template <br />

Base inline power(const Base& x, const Exponent);<br />

template <br />

double inline power(const double& x, const double& y); // Do not use this<br />

Un<strong>for</strong>tunately many of such specializations are ignored. There<strong>for</strong>e, we give the following<br />

Advise<br />

Do not use function template specialization!<br />

To specialize a function to one specific type or type tuple as above, we can simply use overloading.<br />

This works better and is even simpler. Back to our example, assume we have an entirely<br />

generic power method. 9 In the case that both arguments are double we want nevertheless use<br />

the standard implementation hoping that some caffeine-drugged geeks figured out an incredibly<br />

fast assembler hack <strong>for</strong> our plat<strong>for</strong>m and put it in our Linux distribution. Excited by the<br />

incredible per<strong>for</strong>mance — even if it is only the hope <strong>for</strong> it — we overload our power function<br />

as follows:<br />

#include <br />

template <br />

Base inline power(const Base& x, const Exponent)<br />

8 TODO: picture<br />

9 TODO: Anybody an idea <strong>for</strong> an implementation? Or a better example?

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

Saved successfully!

Ooh no, something went wrong!