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.

Meta-programming<br />

Chapter 5<br />

‘Meta-programming’ is actually discovered by accident. Erwin Unruh wrote in the early 90’s<br />

a program that printed prime number as error messages. This showed that C ++ compilers can<br />

compute. Because the language has changed since Unruh wrote the example, here is a version<br />

adapted to today’s standard C ++:<br />

// Prime number computation by Erwin Unruh<br />

template struct D { D(void∗); operator int(); };<br />

template struct is prime {<br />

enum { prim = (p==2) || (p%i) && is prime2?p:0), i−1> :: prim };<br />

};<br />

template struct Prime print {<br />

Prime print a;<br />

enum { prim = is prime::prim };<br />

void f() { D d = prim ? 1 : 0; a.f();}<br />

};<br />

template struct is prime { enum {prim=1}; };<br />

template struct is prime { enum {prim=1}; };<br />

template struct Prime print {<br />

enum {prim=0};<br />

void f() { D d = prim ? 1 : 0; };<br />

};<br />

main() {<br />

Prime print a;<br />

a.f();<br />

}<br />

When tried to compile with g++ 4.1.2, one will observe the following error message: TODO:<br />

Need English error message.<br />

TODO: Ask Erwin Unruh if we can use his example.<br />

After people realized the computational power of the C ++ compiler, it was used to realize very<br />

powerful per<strong>for</strong>mance optimization techniques. In fact, one can per<strong>for</strong>m entire applications<br />

during compile time. Jeremiah Wilcock once wrote a Lisp interpreter that evaluated Lisp<br />

133

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

Saved successfully!

Ooh no, something went wrong!