- Examples
In this lesson, we will look at a few examples of class templates.
We'll cover the following...
Example 1
Press + to interact
// templateClassTemplate.cpp#include <iostream>class Account{public:explicit Account(double amount=0.0): balance(amount){}void deposit(double amount){balance+= amount;}void withdraw(double amount){balance-= amount;}double getBalance() const{return balance;}private:double balance;};template <typename T, int N>class Array{public:Array()= default;int getSize() const;private:T elem[N];};template <typename T, int N>int Array<T,N>::getSize() const {return N;}int main(){std::cout << std::endl;Array<double,10> doubleArray;std::cout << "doubleArray.getSize(): " << doubleArray.getSize() << std::endl;Array<Account,1000> accountArray;std::cout << "accountArray.getSize(): " << accountArray.getSize() << std::endl;std::cout << std::endl;}
Explanation
-
We created two
Array
class objects, i.e.,doubleArray
andaccountArray
in lines 45 and 48. -
By calling the generic function
getSize()
in line 37, we can access the size of different objects.
Example 2
Press + to interact
// templateClassTemplateMethods.cpp#include <algorithm>#include <iostream>#include <vector>template <typename T, int N>class Array{public:Array()= default;template <typename T2>Array<T, N>& operator=(const Array<T2, N>& arr){elem.clear();elem.insert(elem.begin(), arr.elem.begin(), arr.elem.end());return *this;}int getSize() const;std::vector<T> elem;};template <typename T, int N>int Array<T, N>::getSize() const {return N;}int main(){Array<double, 10> doubleArray{};Array<int, 10> intArray{};doubleArray= intArray;Array<std::string, 10> strArray{};Array<int, 100> bigIntArray{};// doubleArray= strArray; // ERROR: cannot convert ‘const std::basic_string<char>’ to ‘double’// doubleArray= bigIntArray; // ERROR: no match for ‘operator=’ in ‘doubleArray = bigIntArray}
...