C++函数模板一

函数模板是通用的函数描述,使用泛型来定义函数,通过将类型作为参数传递给模板,可使编译器生成该类型的函数。

#include <QCoreApplication>
#include<QDebug>
#include<vector>
#include<iostream>
using namespace std;


template<typename T>
T getSumNum(T &t1,T &t2)
{
    return t1+t2;
}

template<typename T>
void swap2(T &a,T &b)
{
    T temp;
    temp = a;
    a = b;
    b = temp;
}


int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    float a1 = 10;
    float b =20.4f;
    QVector<float> V1(5);
    QVector<float> V2(5);
    for(int i= 0;i<5;i++)
    {
        V1.push_back(i*10.5);
    }
    for(int i= 0;i<5;i++)
    {
        V2.push_back(i*20.5);
    }

    swap2<float>(a1,b);
    qDebug()<<a1<<b;
    qDebug()<<getSumNum<float>(a1,b);
    qDebug()<<" V1,V2 "<<getSumNum<QVector<float>>(V1,V2);
    //    qDebug()<<getSumNum(10,20);
    //    qDebug()<<getSumNum(10.3,20.3);

    return a.exec();
}


猜你喜欢

转载自blog.csdn.net/weixin_41882459/article/details/114015214