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.

6.5. BARTON-NACKMAN TRICK 193<br />

6.4.2 Const Cast<br />

const cast adds or removes the attributes const and/or volatile. The key word volatile in<strong>for</strong>ms the<br />

compiler that a variable can be modified by other programs. It is there<strong>for</strong>e not hold or cached<br />

in registers and accessed each time memory. This feature is not used in this script. Adding<br />

an attribute is an implicit conversion in C ++. That is one can always assign an expression<br />

to an variable of the same type with extra attributes without the need <strong>for</strong> a cast. Removing<br />

an attribute requires a const cast and should be only done when unavoidable, e.g. to interface<br />

old-style software that is lacking appropriate const attributes.<br />

6.4.3 Reinterpretation Cast<br />

This is the most aggressive <strong>for</strong>m of casting and not used in this script. It takes an address or an<br />

object’s memory location and interprets the bits there as it was of the target type. One can <strong>for</strong><br />

instance change a single bit in a floating point number by casting it to a bit chain. It is more<br />

important <strong>for</strong> programming hardware drivers than complex flux solvers. Needless to say that<br />

reinterpret cast is one of the most efficient ways to undermine the portability of an application.<br />

6.5 Barton-Nackman Trick<br />

This section describes the ‘Curiously Recurring Template Pattern’ (CRTP). It was introduced<br />

by John Barton and Lee Nackman [?] and is there<strong>for</strong>e also referred to as the ‘Barton-<br />

Nackman Trick’.<br />

6.5.1 A Simple Example<br />

⇒ crtp simple example.cpp<br />

We will explain this with a simple example. Assume we have a class point with an equality<br />

operator:<br />

class point<br />

{<br />

public:<br />

point(int x, int y) : x(x), y(y) {}<br />

bool operator==(const point& that) const { return x == that.x && y == that.y; }<br />

private:<br />

int x, y;<br />

};<br />

We can program the unequality by using common sense or by applying de Morgan’s law:<br />

bool operator!=(const point& that) const { return x != that.x || y != that.y; }<br />

Or we can simplify our live and just negate the result of the equality:<br />

bool operator!=(const point& that) const { return !(∗this == that); }

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

Saved successfully!

Ooh no, something went wrong!