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.

134 CHAPTER 5. META-PROGRAMMING<br />

expression during a C ++ compilation [?]. Todd Veldhuizen showed that the template type<br />

system of C ++ is Turing complete [?].<br />

On the other hand, excessive usage of meta-programming techniques can end in quite long<br />

compile times. Entire research projects were cancelled after many millions dollars of funding<br />

because even short applications of less than 20 lines took weeks of compile time on parallel<br />

computers. We know people who managed to produce a 18 MB error message (it came mainly<br />

from one single error). Nevertheless, the authors used a fair amount of meta-programming in<br />

their scientific projects and could still avoid exhaustive compile times. 1 Also compilers improved<br />

significantly in the last decade. Meanwhile the compile time grew quadratically in the template<br />

instantiation depth in old compilers, today compile grows only linearly [?].<br />

5.1 Let the Compiler Compute<br />

Typical introduction examples <strong>for</strong> meta-programming are factorial and Fibonacci numbers. It<br />

is computed recursively:<br />

template <br />

struct fibonacci<br />

{<br />

static const long value= fibonacci::value + fibonacci::value;<br />

};<br />

template <br />

struct fibonacci<br />

{<br />

static const long value= 1;<br />

};<br />

template <br />

struct fibonacci<br />

{<br />

static const long value= 1;<br />

};<br />

Note that we need the specialization <strong>for</strong> 1 and 2 to terminate the recursion. The following<br />

definition:<br />

template <br />

struct fibonacci<br />

{<br />

static const long value= N < 3 ? 1 : fibonacci::value + fibonacci::value; // error<br />

};<br />

ends in an infinite compile loop. For N = 2, the compiler would evaluate the expression:<br />

template <br />

struct fibonacci<br />

{<br />

static const long value= 2 < 3 ? 1 : fibonacci::value + fibonacci::value; // error<br />

};<br />

1 TODO: Oder René?

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

Saved successfully!

Ooh no, something went wrong!