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.

5.2. PROVIDING TYPE INFORMATION 143<br />

Constant types match both definitions but the second one is more specific and there<strong>for</strong>e picked<br />

by the compiler. Non-constant types match only the first one. Note that the constancy of<br />

template parameters is not considered, e.g., view is not regarded constant.<br />

Compile-time Branching<br />

The other tool we need <strong>for</strong> our view is a type selection depending on a logical condition. Introduced<br />

was this technology by Krzysztof Czarnecki 9 and Ulrich W. Eisenecker [CE00]<br />

This can be achieved by a rather simple implementation<br />

1 template <br />

2 struct if c<br />

3 {<br />

4 typedef ThenType type;<br />

5 };<br />

6<br />

7 template <br />

8 struct if c<br />

9 {<br />

10 typedef ElseType type;<br />

11 };<br />

Listing 5.2: Compile-time if<br />

When this template is instantiated with a logical expressions and two type, only the general<br />

definition in line 1 matches when the first argument evaluates to true and the ‘ThenType’ is used<br />

in the type definition. If the first argument evaluates to false then the specialization in line 7<br />

is more specific so that the ‘ElseType’ is used. Like many ingenious inventions it is very simple<br />

once it is found.<br />

This allows us to define funny things like using double <strong>for</strong> temporaries when our maximal<br />

iteration number is larger than 100 other float:<br />

typedef tst::if c 100, double, float>::type tmp type;<br />

std::cout ≪ ”typeid = ” ≪ typeid(tmp type).name() ≪ ’\n’;<br />

Needless to say that ‘max iter’ must be known at compile time. Admittedly, the example does<br />

not look extremely useful and the meta-if is not so important in small isolated code snippets.<br />

On the other hand, <strong>for</strong> the development of large generic software packages, it becomes extremely<br />

important.<br />

A convenience function as defined in the Meta-Programming Library [GA04] is ‘if ’<br />

template <br />

struct if<br />

: if c<br />

{};<br />

It expects as first argument a type with a static const member named value and convertible to<br />

bool. In other words, it selects the type based on the value of condition (and saves typing 8<br />

characters).<br />

9 Zu dem Zeitpunkt war er Doktorand an der TU Ilmenau.

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

Saved successfully!

Ooh no, something went wrong!