Qt实现简单函数模板和类模板

函数模板

函数模板时用于生产函数的,T是类型参数,代表类型,编译器由模板自动生成函数时,会用具体的类型名对模板中所有的类型参数进行替换,其他部分则原封不动地保留。
widget.h

#ifndef WIDGET_H
#define WIDGET_H

#include <QWidget>

namespace Ui {
    
    
class Widget;
}

class Widget : public QWidget
{
    
    
    Q_OBJECT

public:
    explicit Widget(QWidget *parent = 0);
    ~Widget();

    //头文件声明一个函数模板
    template<class T>
    void swap(T & a,T & b);
private:
    Ui::Widget *ui;
};

#endif // WIDGET_H

widget.cpp

#include "widget.h"
#include "ui_widget.h"
#include <QDebug>
#include "classtemplate.h"

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    
    
    ui->setupUi(this);

    int num1 = 1;
    int num2 = 3;
    swap(num1,num2);//函数模板生成的模板函数
    qDebug()<<"["<<__FILE__<<"]"<<__LINE__<<__FUNCTION__<<" "<<num1;
    qDebug()<<"["<<__FILE__<<"]"<<__LINE__<<__FUNCTION__<<" "<<num2;

    double num3 = 2.5;
    double num4 = 3.6;
    swap(num3,num4);
    qDebug()<<"["<<__FILE__<<"]"<<__LINE__<<__FUNCTION__<<" "<<num3;
    qDebug()<<"["<<__FILE__<<"]"<<__LINE__<<__FUNCTION__<<" "<<num4;
}
Widget::~Widget()
{
    
    
    delete ui;
}
//在cpp文件实现函数模板
template<class T>
void Widget::swap(T &a, T &b)
{
    
    
    T temp;
    temp = a;
    a = b;
    b = temp;
}

打印输出

[ ..\templateTest\widget.cpp ] 15 Widget::Widget   3
[ ..\templateTest\widget.cpp ] 16 Widget::Widget   1
[ ..\templateTest\widget.cpp ] 21 Widget::Widget   3.6
[ ..\templateTest\widget.cpp ] 22 Widget::Widget   2.5

类模板

类模板在STL中应用广泛,比如list、vector等都是类模板
classtemplate.h

#ifndef CLASSTEMPLATE_H
#define CLASSTEMPLATE_H

#include <QObject>
using namespace std;

template<class T1,class T2>
class ClassTemplate
{
    
    
public:
    T1 key;
    T2 value;
    ClassTemplate(T1 k,T2 v):key(k),value(v){
    
    }
    bool operator < (const ClassTemplate<T1,T2>& p) const;
};

//类模板的成员函数放到类定义外面时的写法:
template<class T1,class T2>
bool ClassTemplate<T1,T2>::operator < (const ClassTemplate<T1,T2>& p) const
{
    
    
    return key < p.key;
}

#endif // CLASSTEMPLATE_H

调用示例

    ClassTemplate<QString,int> student("Tom",19);//使用类模板实例化一个模板类,再使用模板类实例化一个对象student
    qDebug()<<"["<<__FILE__<<"]"<<__LINE__<<__FUNCTION__<<" "<<student.key;
    qDebug()<<"["<<__FILE__<<"]"<<__LINE__<<__FUNCTION__<<" "<<student.value;

打印输出

[ ..\templateTest\widget.cpp ] 25 Widget::Widget   "Tom"
[ ..\templateTest\widget.cpp ] 26 Widget::Widget   19

猜你喜欢

转载自blog.csdn.net/weixin_40355471/article/details/110739695