When using a structure as a formal parameter to assign a value to another structure, you only want to change the parameters of part of the structure content without changing all the parameters. You can use display reification.
For a given function name, there can be non-template functions, template functions, and display materialized template functions and their overloaded templates.
The prototype and definition of the display materialization should start with template<> and indicate the type by name.
Reification takes precedence over regular templates, and non-template functions take precedence over reification and regular templates.
The following are the non-template functions, template functions, and concrete prototypes used to exchange job structures:
//非模板函数原型
void swap(job &,job &);
//模板原型
template<typename T>
void swap(T &,T&);
//显示具体化
template<>void swap<job>(job &,job &);
demo example:
#include <QCoreApplication>
#include<QDebug>
#include<vector>
#include<iostream>
using namespace std;
template<typename T>
void swapData(T& a,T &b)
{
T temp;
temp = a;
a = b;
b = temp;
}
struct job
{
char name[40];
double salary;
int floor;
};
//显示具体化
template<>void swapData<job>(job &j1,job &j2)
{
double t1;
int t2;
t1 = j1.salary;
j1.salary = j2.salary;
j2.salary = t1;
t2 = j1.floor;
j1.floor = j2.floor;
j2.floor = t2;
}
void show(job &j)
{
cout<<"name: "<<j.name<<" salary: "<<j.salary<<" floor: "<<j.floor<<endl;
}
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
int i = 10,j=20;
swapData(i,j);
cout<<"\n";
job sue = {"su",7000,2};
job alice = {"alice",12121,3};
show(sue);
show(alice);
swapData(sue,alice);
cout<<"after switch ....";
show(sue);
show(alice);
return a.exec();
}