Post

[C++] Chap 13 - Templates

[C++] Chap 13 - Templates

C++ templates

  • Allows very “general” definitions for functions and classes
  • Type names are considered as “parameters” instead of actual types
  • precise definition is determined at the run-time
1
2
3
4
5
6
7
8
template<class T> // class is considered as reserved word (typename)
void swapValues(T& var1, T& var2)
{
	T temp;
	temp = var1;
	var1 = var2;
	var2 = temp;
}
  • template<class T> tells compiler what’s comming next is “Template”
  • T is type parameter, can use other than T but it is traditional
  • Compiler only generates definitions when required.
  • Must put template<class T> in both declaration, definition

Multiple Type params

  • template<class T1, class T2>
  • not typical.
  • Cannot have unused template parameters. → Each should be used at least once in the definition

Inappropriate Types in Templates

  • Can use any type in template for which code makes “sense”
  • e.g.) swapValues() template function,
1
2
int a[10], b[10];
swapValeus(a, b); //Invalid
  • Since arrays cannot be “Assigned”

Class Templates

  • Templates can be used to generalize in class definition
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
template<class T>
class Pair
{
public:
	Pair();
	Pair(T firstValue, T SecondValue);
	void setFirst(T newValue);
	void setSecond(T newValue);
	T getFirst() const;
	T getSecond() const;
private:
	T first;
	T second;
};

template<class T>
Pair<T>::Pair(T firstValue, T secondValue) : first(firstValue), second(SecondValue) {}
template<class T>
void Pair<T>::setFirst(T newValue){ first = newValue}

//Must include template<class T> both declaration, definition. 
// Type of class templates is Classname<T>
  • Class name before :: is Pair<T>
  • but constructor and destructor’s name is just Pair and ~Pair
  • class Templates can be used as function parameter
  • int addUP(const Pair<int>& thePair);
  • vector<T>, basic_string<T> is a template

Class Templates within Function Templates

1
2
3
template<class T>
T addUp(const Pair<T>* thePair);
// Precondition : operator T is defined for values of type T.

Restrictions on Type parameter on Class Templates

  • Only reasonable types can be substituted for T
  • Assignment operator(=), copy constructor must be “well-behaved”
  • T involves pointers, then destructor must be suitable

Type Definitions

  • Can define new class type name
1
typedef Pair<int> PairOfInt;

Friends and Templates

  • Friend functions can be used with template classes
    • Same as with ordinary classes
    • Simply requires friend keyword when appropriate

Templates and Inheritance

  • Derived template classes
    • Can be derived from template or non-template class
    • Derived class from a template class is naturally a template class
  • Syntax is the same as ordinary class derived from an ordinary class
This post is licensed under CC BY 4.0 by the author.