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.

90 CHAPTER 4. GENERIC PROGRAMMING<br />

}<br />

else<br />

return b;<br />

Note that the function body is exactly the same <strong>for</strong> both int and double.<br />

With the template mechanism we can write just one generic implementation:<br />

template <br />

T inline max (T a, T b)<br />

{<br />

if (a > b)<br />

return a;<br />

else<br />

return b;<br />

}<br />

The function can be used in the same way as the overloaded functions:<br />

std::cout ≪ ”The maximum of 3 and 5 is ” ≪ max(3, 5) ≪ ’\n’;<br />

std::cout ≪ ”The maximum of 3l and 5l is ” ≪ max(3l, 5l) ≪ ’\n’;<br />

std::cout ≪ ”The maximum of 3.0 and 5.0 is ” ≪ max(3.0, 5.0) ≪ ’\n’;<br />

In the first case, ‘3’ and ‘5’ are literals of type int and the max function is instantiated to<br />

int inline max (int, int);<br />

Likewise the second and third call of max instantiate<br />

long inline max (long, long);<br />

double inline max (double, double);<br />

as the literals are interpreted as long and double.<br />

In the same way the template function can be called with variables and expressions:<br />

unsigned u1= 2, u2= 8;<br />

std::cout ≪ ”The maximum of u1 and u2 is ” ≪ max(u1, u2) ≪ ’\n’;<br />

std::cout ≪ ”The maximum of u1∗u2 and u1+u2 is ” ≪ max(u1∗u2, u1+u2) ≪ ’\n’;<br />

Here the function is instantiated <strong>for</strong> short.<br />

Instead of typename one can also write class in this context but we do not recommend this<br />

because typename expresses better the intention of a generic function.<br />

What does instantiation mean? When you write a non-generic function, the compiler reads<br />

its definition, checks <strong>for</strong> errors, and generates executable code. When the compiler processes<br />

a generic function’s definition it only checks certain errors (parsing errors) and generates no<br />

executable code. For instance:<br />

template <br />

T inline max (T a, T b)<br />

{<br />

if a > b // Error !<br />

return a;<br />

else<br />

return b;<br />

}

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

Saved successfully!

Ooh no, something went wrong!