<<

Introduction to Core C++

Lecture 04: Template Functions and Template Classes

Massimiliano Culpo1

1CINECA - SuperComputing Applications and Innovation Department

26.02.2013

M.Culpo (CINECA) Introduction to C++ 26.02.2013 1 / 19 Template functions Template declarations Template declarations (§14)

A template defines family of classes or functions:

1 template 2 T const& max (T const& a , T const& ) { 3 // ifa < b then useb else usea 4 returna < b ? b : a ; 5 }

A template declaration shall: declare or define a function or a class define a member function, a member class or a static data member define a member template of a class or class template A template declaration is also a definition if its declaration defines a function, a class, or a static data member.

M.Culpo (CINECA) Introduction to C++ 26.02.2013 2 / 19 Template functions Template parameters Template parameters (§14.1)

There are three kinds of allowed template parameters: non-type template parameters, type template parameters and template template parameters. A non-type template parameter shall be either an integral or enumeration type, a pointer/reference to object or function or a pointer to member.

1 template voidf () { 2 ++; // error 3 &x ; // OK 4 &i ; // error 5 i t& i = i ; // error 6 const int& c r i = i ; // OK 7 }

A non-type template parameter cannot be assigned to or in any other way have its value changed.

M.Culpo (CINECA) Introduction to C++ 26.02.2013 3 / 19 Template functions Template parameters Template parameters (§14.1)

The keyword class followed by an unqualified-id names a type parameter:

1 template c l a s s Map { 2 std :: vector key ; 3 std :: vector value ; 4 } ;

Template classes may also be used as template parameters:

1 template c l a s sC > c l a s s Map { 3 C key ; 4 C value ; 5 } ;

M.Culpo (CINECA) Introduction to C++ 26.02.2013 4 / 19 Template functions Template parameters Template parameters (§14.1)

A default argument may be specified for any kind of template parameter:

1 template c l a s sA ; 2 3 template s t r c tB {} ; 4 template