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.

102 CHAPTER 4. GENERIC PROGRAMMING<br />

∼vector() { if (data) delete [] data ; }<br />

private:<br />

int my size;<br />

unsigned char∗ data ;<br />

};<br />

One thing we realize is that the default constructor and the destructor are identic with the<br />

non-specialized version (in the following also referred to as general version). Un<strong>for</strong>tunately, this<br />

is not ‘inherited’ to the specialization. If we write a specialization we have to define everything<br />

from scratch. We are free to omit member functions or variables from the general but <strong>for</strong> the<br />

sake of consistency we do this only <strong>for</strong> good reasons, <strong>for</strong> very good reasons. For instance, we<br />

might omit the operator+ because we have no addition <strong>for</strong> bool. The constant access operator<br />

is implemented with shifting and bit masking:<br />

template class vector<br />

{<br />

bool operator[](int i) const { return (data[i/8] ≫i%8) & 1; }<br />

};<br />

The mutable access is trickier because we cannot refer to single bits. The trick is to returns<br />

some helper type — called ‘Proxy’ — that can per<strong>for</strong>m the assignment and returning boolean<br />

from a byte reference and the position within the byte.<br />

template class vector<br />

{<br />

vector bool proxy operator[](int i)<br />

{<br />

return vector bool proxy(data[i/8], i%8);<br />

}<br />

};<br />

Let us now implement our proxy:<br />

class vector bool proxy<br />

{<br />

public:<br />

vector bool proxy(unsigned char& byte, int p) : byte(byte), mask(1 ≪ p) {}<br />

private:<br />

unsigned char& byte;<br />

unsigned char mask;<br />

};<br />

To simplify further operations we create a mask that has 1 on the position in question and 0<br />

on all other positions.<br />

The reading access is implemented by simply masking in the conversion operator:<br />

class vector bool proxy<br />

{<br />

operator bool() const { return byte & mask; }<br />

};<br />

Setting a bit is realized by an assignment operator <strong>for</strong> bool:

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

Saved successfully!

Ooh no, something went wrong!