Search⌘ K

- Examples

Explore practical C++ template examples focusing on type parameters, template-template parameters, and how to implement a matrix class using standard containers. Understand how typeid helps identify parameter types and how templates enhance flexibility and code reuse. This lesson prepares you to apply template concepts effectively in your C++ projects.

Example 1: Type Parameter #

C++
// templateTypeParameter.cpp
#include <iostream>
#include <typeinfo>
class Account{
public:
explicit Account(double amt): balance(amt){}
private:
double balance;
};
union WithString{
std::string s;
int i;
WithString():s("hello"){}
~WithString(){}
};
template <typename T>
class ClassTemplate{
public:
ClassTemplate(){
std::cout << "typeid(T).name(): " << typeid(T).name() << std::endl;
}
};
int main(){
std::cout << std::endl;
ClassTemplate<int> clTempInt;
ClassTemplate<double> clTempDouble;
ClassTemplate<std::string> clTempString;
ClassTemplate<Account> clTempAccount;
ClassTemplate<WithString> clTempWithString;
std::cout << std::endl;
}

Explanation #

In the code above, we are identifying the type of different data types that we have passed in the parameter list. We can ...