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で広く使用されています。たとえば、リスト、ベクターなどはすべてクラステンプレート
です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