/*
演示: 模板函数及其特化函数的使用
*/
#include <stdio.h>
#include <iostream>
#include <string>
#include <map>
using namespace std;
template<typename T>
T add(T n1, T n2) // 通用模板函数
{
return n1 + n2;
}
//template<> int add(int n1, int n2) // 模板函数特化1
template<> int add<int>(int n1, int n2) // 模板函数特化1: 这种写法也可以
{
return n1 - n2;
}
//template<> float add(float n1, float n2) // 模板函数特化2
template<> float add<float>(float n1, float n2) // 模板函数特化2
{
return n1 * n2;
}
int main()
{
double x1 = 2.2;
double x2 = 1.4;
double x = add(x1, x2); // 调用: 通用模板函数
cout << x << endl;
int a1 = 2.2;
int a2 = 1.4;
int a = add(a1, a2); // 调用: 模板函数特化1
cout << a << endl;
float x11 = 2.2;
float x21 = 1.4;
float x31 = add(x11, x21); // 调用: 模板函数特化2
cout << x31 << endl;
long a11 = 2.2;
long a21 = 1.4;
long a31 = add(a11, a21); // 调用: 通用模板函数
cout << a31 << endl;
return 0;
}
/*
运行情况:
D:\profile\Desktop\test>make
g++ -o a.exe a.cpp
D:\profile\Desktop\test>a
3.6
1
3.08
3
*/
函数模板特化(一)
最新推荐文章于 2024-08-25 15:12:08 发布