一、函數模板
template.h
#pragma once
#include <iostream>
#include <map>
template <typename T>
T funcadd(T a, T b)
{
T addhe = a + b;
return addhe;
}
template <typename T, int a, int b=7>
int funcadd1(T c)
{
int addhe = (int)c + a + b;
return addhe;
}
template <typename T>
typename T::size_type getLength(const T &c)//typedef int string:size_type,T::size_type是一個類型,所以前面要加上typename
{
if (c.empty())
return 0;
return c.size();
}
template <typename T1, typename T2, typename T3>
T1 sum(T2 i, T3 j)
{
T1 result = i + j;
return result;
}
main.cpp
#include <iostream>
#include "template.h"
using namespace std;
int main()
{
cout << "Hello World!\n";
funcadd(5, 6);
funcadd1<int, 5, 6>(7);//必須強行指定類型
string mytest = "I love China";
string::size_type size = getLength(mytest);
sum<int>(22, 33);//必須強行指定類型
}
函數模板:默認自行推倒類型,如需要,可強行指定。
二、類模板、類成員函數模板
template.h
#pragma once
#include <iostream>
#include <map>
template <typename C>
class A
{
public:
template <typename T2>
A(T2 v1, T2 v2);
template <typename T>
void myft(T tmft);
};
template <typename C>
template <typename T2>
A<C>::A(T2 v1, T2 v2)
{
}
template <typename C>
template <typename T>
void A<C>::myft(T tmft)
{
std::cout << tmft << std::endl;
}
main.cpp
#include <iostream>
#include "template.h"
using namespace std;
int main()
{
A<float> a(1.3f, 1.4f);
a.myft(3);
return 1;
}
模板類聲明和類定義必須在同一個.h文件中。