From 6bf234be9f8458053f10572b1fe6b6210a532ea0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=85=A8=E9=83=A8=E9=83=BD=E6=83=B3=E5=AD=A6=E6=80=8E?= =?UTF-8?q?=E4=B9=88=E5=8A=9E?= <2434858409@qq.com> Date: Tue, 5 Apr 2022 21:00:53 +0800 Subject: [PATCH] =?UTF-8?q?=E4=B8=8A=E4=BC=A0=E6=96=B0=E6=96=87=E4=BB=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../twoswap.cpp" | 72 +++++++++++++++++++ 1 file changed, 72 insertions(+) create mode 100644 "Ch8\345\207\275\346\225\260\346\216\242\345\271\275/\345\207\275\346\225\260\346\250\241\346\235\277/twoswap.cpp" diff --git "a/Ch8\345\207\275\346\225\260\346\216\242\345\271\275/\345\207\275\346\225\260\346\250\241\346\235\277/twoswap.cpp" "b/Ch8\345\207\275\346\225\260\346\216\242\345\271\275/\345\207\275\346\225\260\346\250\241\346\235\277/twoswap.cpp" new file mode 100644 index 0000000..efab3cf --- /dev/null +++ "b/Ch8\345\207\275\346\225\260\346\216\242\345\271\275/\345\207\275\346\225\260\346\250\241\346\235\277/twoswap.cpp" @@ -0,0 +1,72 @@ +//twoswap.cpp -- specialization overrides a template +#include +template +void Swap(T& a, T& b); + +struct job +{ + char name[40]; + double salary; + int floor; +}; + +//explicit specialization for the job type +template <> void Swap(job& j1, job& j2); +void Show(job& j); + + + +int main(void) +{ + using namespace std; + cout.precision(2); + cout.setf(ios::fixed, ios::floatfield); + int i = 10, j = 20; + cout << "i, j = " << i << ", " << j << ".\n"; + + + job sue = { "Susan Yaffee",73000.60,7 }; + job sidney = { "Sidney Taffee",78060.72,9 }; + cout << "Before job swapping:\n"; + Show(sue); + Show(sidney); + Swap(sue, sidney); //uses void Swap(job&,job&) + + + cout << "After job swapping:\n"; + Show(sue); + Show(sidney); + cin.get(); + + + return 0; +} + +template +void Swap(T& a, T& b) //general version +{ + T temp; + temp = a; + a = b; + b = temp; +} + +//swaps just the salary and floor fields of a job structure +template<>void Swap(job& j1, job& j2) //specialization +{ + 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) +{ + using namespace std; + cout << j.name << ": $" << j.salary + << " on floor " << j.floor << endl; +} -- GitLab