Why templates
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<int> v;
for (int i = 0; i < 5; i++)
v.push_back(i);
// v.pop_back();
cout << "size=" << v.size() << endl;
vector<int>::iterator p;
for (p = v.begin(); p < v.end(); p++)
{
int data = *p;
cout << "data:" << *p << endl;
}
}
// g++ main.cpp && ./a.out
模板1
function template
#include <iostream>
using namespace std;
template <class T>
void swap_2(T& x, T& y){
T temp = x;
x = y;
y = temp;
}
int main()
{
int x = 5;
int y = 7;
swap_2(x, y);
cout << "x=" << x << ", y=" << y << endl;
}
#include <iostream>
#include <string>
using namespace std;
template <class T>
void swap_2(T &x, T &y)
{
T temp = x;
x = y;
y = temp;
}
// g++ main.cpp && ./a.out
int main()
{
string x("world");
string y("hello");
swap_2(x, y);
cout << x << y << endl;
}
A template function is an instantiation of a function template.
Interactions
- Only exact match on types is used
- No conversion operations are applied
- swap(int, int); //ok
- swap(double, double); //ok
- swap(int, double); //error
- Even implicit conversions are ignored
- Template functions and regular functions coexist
Overloading rules
Function Instantiation
Class templates
类模板里的每个函数都是函数模板
模板2
A simple sort function
// bubble sort -- don't use it!
template<class T>
void sort(vector<T> &arr) {
const size_t last = arr.size() - 1;
for (int i = 0; i < last; i++) {
for (int j = last; i < j; j--) {
if (arr[j] < arr[j - 1]) {
swap_2(arr[j], arr[j - 1]);
}
}
}
}
Templates can use multiple types
template<class K, class V>
class HashMap {
const V &get(const K &) const;
void put(K key,V value);
};