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.

4.11. EXERCISES 129<br />

1<br />

2<br />

3<br />

4<br />

function gcd(a, b):<br />

if b = 0 return a<br />

else return gcd(b, a mod b)<br />

Then write an integral metafunction that executes the same algorithm but at compile time.<br />

Your metafunction should be of the following <strong>for</strong>m:<br />

template <br />

struct gcd meta {<br />

static int const value = ... ;<br />

} ;<br />

i.e. gcd meta::value is the GCD of a and b. Verify whether the results correspond with your<br />

C ++ function gcd().<br />

4.11.6 Overloading of functions<br />

Overloading of functions is possible <strong>for</strong> different types, e.g.<br />

void foo( int i ) { ... }<br />

void foo( double d ) { ... }<br />

This is an exercise on another <strong>for</strong>m of overloading: based on a boolean meta expression. We<br />

will use the Boost functions enable if and disable if <strong>for</strong> this exercise.<br />

#include <br />

#include <br />

template <br />

typename boost::enable if< boost::is integral, T >::type foo( T const& v ) {<br />

return v ;<br />

}<br />

template <br />

typename boost::disable if< boost::is integral, T >::type foo( T const& v ) {<br />

return std::floor( v ) ;<br />

}<br />

If we call e.g. foo(5);, the compiler uses the special version <strong>for</strong> integers:<br />

template <br />

T foo( T const& v ) {<br />

return v ;<br />

}<br />

If we call e.g. foo(5.0);, the compiler uses the special version <strong>for</strong> types that are not integral:<br />

template <br />

T foo( T const& v ) {<br />

return std::floor( v ) ;<br />

}

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

Saved successfully!

Ooh no, something went wrong!