C++22——模板

template < class T > //声明
void swap(T& x,T& y){
    T temp=x;
    x=y;
    y=temp;
}

void swap(int& x,int& y){
    int temp=x;
    x=y;
    y=temp;
}

int i=3;int j=4;
swap(i,j);	//调用具体的int swap

float k=4.5;float m=3.7;
swap(k,m);	//没有float swap 使用模板swap

std::string s("Hello");
std::string t("World");
swap(s,t);	//std::string swap	
swap(int,int);	//ok
swap(float,float);	//ok
swap(int,float);	//error
//在调用模板的过程中,不可以进行类型转换
void f(float i,float k){ };
template <class T>
void f(T t,T u){ };
f(1.0,2.0);
f(1,2);
f(1,2.0);
template <class T>
void foo(void){ }
foo<int>();		//T是int
foo<float>();	//T是float
template <class T>
class Vector{
public:
    Vector(int);
    ~Vector();
    Vector(const Vector&);
    Vector& operator=(const Vector&);
    T& operator[](int);
private:
    T* m_elements;
    int m_size;
};
//类里面每一个函数都是函数模板
template <class T>
Vector<T>::Vector(int size):m_size(size){
    m_elements=new T[m_size];
}   

template <class T>
T& Vector<T>::operator[](int index){
    if(index <m_size&&index>0){
        return m_elements[index];
    }else{
        ...
    }
}

Vector<int> v1(100);
Vector<Complex> v2(256);

v1[20]=10;
v2[20]=v1[10];//如果使用构造函数把int变成Complex,本句就正确
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(arr[j],arr[j-1]);
        }
    }
}
vector<int> vi(4);
vi[0]=4;vi[1]=3;vi[2]=7;vi[3]=1;
sort(vi);		//sort(vector<int>& )

vector<string> vs;
vs.push_back("Fred");
vs.push_back("Wilma");
vs.push_back("Barney");
vs.push_back("Dino");
vs.push_back("Prince");
sort(vs);		//sort(vector<string>& )
//ps:sort需要使用重载过后的<进行比较
template<class Key,class Value>
class HashTable{
    const Value& lookup(const Key& ) const;
    void install(const Key&,const Value&);
    ...
};

注意:Vector< Vector<double *> >记得加空格,不然可能会报错

Vector< int (*)(Vector<double>&,int)>函数指针,返回int型;参数表:第一项是个Vector的引用,里面放的是double,第二项是个int

template <class T,int bounds=100>
class FixedVector{
public:
    FixedVector();
    //...
    T& operator[](int);
private:
    T element[bounds];	//固定大小的数组,但是也是可变的
};

FixedVector<int,50> v1;
FixedVector<int,10*5> v2;
FixedVector<int> v3;		//使用默认值
//模板可以继承非模板类
template <class A>
class Derived:public Base{....}

//模板可以继承模板类
template <class A>
class Derived:public List<A>{....}
//模板和模板之间不能继承,必须要有实例的A,才能继承

//非模板类可以继承模板
class SupervisorGroup : public List<Employee*>{ }
//前面没有template就类,而不是模板

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值