一. 类模板
template<typename T>
class complex
{
public:
complex(T r=0, T i=0)
:re(r), im(r)
{}
complex& operator += (const complex&)
T real() const {return re;}
T imag() const {return im;}
private:
T re, im;
friend complex& __doapl(complex*, const complex&)
};
{
complex<double> c1(2.5, 1.5);
complex<int> c2(2, 6);
...
}
二. 函数模板
- 编译器会对function template进行实参推导。
template<class T>
inline
const T& min(const T& a, const T& b){
return b< a? b : a;
}
stone r1(2,3), r2(3,3), r3;
r3 = min(r1, r2);
class stone{
public:
stone(int w, int h, int we)
: _w(w), _h(h), _weight(we);
{ }
bool operator<(const stone& rhs) const
{return _weight < rhs._weight; }
private:
int _w, _h, _weight;
}
三. 成员模板
template<class T1, class T2>
struct pair{
typrdef T1 first_type;
typedef T2 second_type;
T1 first;
T1 second;
template<class U1, class U2>
pair(const paur<U1, U2>& p)
:first(p.first), second(p.second) {}
};
class Base1{};
class Derived1:public Base1{};
class Base2{};
class Derived2:public Base2{};
pair<Derived1, Derived2> p;
pair<Base1, Base2>p2(p);
pair<Base1, Base2>p2(pair<Derived1, Derived2>());
template<typename _Tp>
class shared_ptr:public __shared_ptr<_Tp>
{
...
template<typename _Tp1>
explicit shared_ptr(_Tp1* __p)
:__shared_ptr<_Tp>(__p){}
...
};
Base1 ptr = new Derived1;
shared_ptr<Base1> sptr(new Derived);
四. 模板特化
template<class Key>
struct hash{};
template<>
struct hash<char>{
size_t operator()(char x) const {return x; }
};
template<>
struct hash<int>{
size_t operator()(int x) const {return x; }
};
template<>
struct hash<long>{
size_t operator()(long x) const {return x; }
};
五. 模板偏特化
template<template T, typename Alloc=>
class vector
{
...
};
template<typename Alloc=...>
class vector<bool, Alloc>
{};
template<template T>
class C
{
...
};
template<typename T>
class C<T*>
{
...
};
template<typename U>
class C<U*>
{
...
};
六. template template parameter,模板模板参数
- <>里 class 和 typename可以共通。
- 容器一般有第二第三参数,平时有默认值。
Xcls<string, List> mylst2; // 错误用法
template<typename T,
typename<typename T> class Container >
class XCls
{
private:
Container<T> c;
public:
....
};
template<typename T>
using Lst=list<T, allocator<T>>;
Xcls<string, Lst> mylst2;
template<typename T,
typename<typename T> class SmartPtr >
class XCls
{
private:
SmartPtr<T> sp;
public:
XCls() : sp(new T){ }
};
Xcls<string, shared_ptr> p1;
Xcls<string, unique_ptr> p2; //错误
Xcls<string, weak_ptr> p3; //错误
Xcls<string, auto_ptr> p4;
网友评论