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 137<br />

struct Magnitude<br />

{<br />

typedef double type;<br />

};<br />

template <br />

struct Magnitude<br />

{<br />

typedef float type;<br />

};<br />

template <br />

struct Magnitude<br />

{<br />

typedef double type;<br />

};<br />

Admittedly, this is rather cumbersome.<br />

We can abbreviate the first definitions by postulating “if we do not know better, we assume<br />

that T’s Magnitude type is T itself.”<br />

template <br />

struct Magnitude<br />

{<br />

typedef T type;<br />

};<br />

This is true <strong>for</strong> all intrinsic types and we handle them all correctly with one definition. A slight<br />

disadvantage of this definition is that it incorrectly applies to all types whose type trait is not<br />

specialized. A set of classes where we know that the above definition is not correct, are all<br />

instantiations of the template class complex. So we define specializations like:<br />

template <br />

struct Magnitude<br />

{<br />

typedef double type;<br />

};<br />

Instead of defining them individually <strong>for</strong> complex, complex, . . . we use a templated<br />

<strong>for</strong>m to treat them all<br />

template <br />

struct Magnitude<br />

{<br />

typedef T type;<br />

};<br />

Now that the type traits are defined we can refactor our function to use it:<br />

template <br />

T inline min magnitude(const T& x, const T& y)<br />

{<br />

using std::abs;<br />

typename Magnitude::type ax= abs(x), ay= abs(y);<br />

return ax < ay ? x : y;<br />

}

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

Saved successfully!

Ooh no, something went wrong!