P. 1
c++ for Beginners

c++ for Beginners

|Views: 13|Likes:
Published by Swathi Sridharan

More info:

Published by: Swathi Sridharan on Feb 22, 2012
Copyright:Attribution Non-commercial

Availability:

Read on Scribd mobile: iPhone, iPad and Android.
download as PDF, TXT or read online from Scribd
See more
See less

02/22/2012

pdf

text

original

A function template definition (or declaration) is always preceded by a template
clause
, which consists of the keyword template and a list of one or more type
parameters. For example,

template T Max (T, T);

declares a function template named Max for returning the maximum of two objects.
T denotes an unspecified (generic) type. Max is specified to compare two objects
of the same type and return the larger of the two. Both arguments and the return
value are therefore of the same type T. The definition of a function template is very
similar to a normal function, except that the specified type parameters can be
referred to within the definition. The definition of Max is shown in Listing 9.35.

Listing 9.35

1
2
3
4
5

template
T Max (T val1, T val2)
{

return val1 > val2 ? val1 : val2;

}

A type parameter is an arbitrary identifier whose scope is limited to the
function itself. Type parameters always appear inside <>. Each type parameter
consists of the keyword class followed by the parameter name. When multiple
type parameters are used, they should be separated by commas. Each specified
type parameter must actually be referred to in the function prototype. The keyword
class cannot be factored out:

template
T3 Relation(T1, T2);

// ok

template
int Compare (T1, T1);

// illegal! T2 not used.

template

// illegal! class missing for T2

int Compare (T1, T2);

For static, inline, and extern functions, the respective keyword must appear after
the template clause, and not before it:

template
inline T Max (T val1, T val2);// ok

inline template

// illegal! inline misplaced

T Max (T val1, T val2);

¨

172

C++ Essentials

Copyright © 2005 PragSoft

You're Reading a Free Preview

Download
scribd
/*********** DO NOT ALTER ANYTHING BELOW THIS LINE ! ************/ var s_code=s.t();if(s_code)document.write(s_code)//-->