qfedu-cpp-level/day6/template/t1.cpp

50 lines
916 B
C++
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// 函数模版
/*
template <class T>
函数返回值 函数名(T &n1, T &n2)
{
// 函数体
}
*/
#include <iostream>
#include <cstring>
#include <cstdlib>
using namespace std;
namespace my
{
// 推荐使用 typename 而不是 class因为 typename 更通用
template <typename T>
void swap(T &a, T &b)
{
a ^= b;
b ^= a;
a ^= b;
}
// 函数模版重载: 用于不同类型的参数
template <typename T1, typename T2>
void swap(T1 &a, T2 &b)
{
a ^= b;
b ^= a;
a ^= b;
}
}
int main()
{
int a = 2, b = 6;
cout << a << ", " << b << endl;
my::swap(a, b); // 自动推演类型: swap<int>(a, b)
cout << a << ", " << b << endl;
char c = 30;
cout << a << ", " << (int)c << endl;
my::swap(a, c); // 自动推演类型
cout << a << ", " << (int)c << endl;
return 0;
}