#pragma once
#include <iostream>
/*/////////////////////////////////////////////
C++(www.cppentry.com) 模板
/////////////////////////////////////////////*/
/*
--- 函数模板 ---
*/
/// 声明
template <typename T1, typename T2>
void TFunc(T1, T2);
/// 一般定义
template <typename T1, typename T2>
void TFunc(T1, T2)
{
std::cout << "一般" << std::endl;
}
/// 偏特化,T2(int)
template <typename T1>
void TFunc(T1, int)
{
std::cout << "偏特化" << std::endl;
}
/// 全特化,T1(char), T2(char)
template <>
void TFunc(char, char)
{
std::cout << "全特化" << std::endl;
}
/// 重载,函数的参数个数不同
template <typename T1>
void TFunc(T1)
{
std::cout << "重载" << std::endl;
}
/// 函数模板不允许默认的参数类型,而类模板允许
// template <typename T1, typename T2=int>
// void DefaultParamFun(T1, T2){}
/// 测试模板函数
void Test_Func()
{
TFunc<int,int>(0, 0); // 一般
TFunc<char>('a', 0); // 偏特化
TFunc('a','a'); // 全特化
TFunc<int>(0); // 重载
std::cout << std::endl;
}
/*
--- 类模板 ---
*/
/// 类模板允许默认的参数类型
template <typename T1, typename T2=int>
class TClass
{
public:
TClass()
{
std::cout << "类模板,一般" << std::endl;
}
template <typename P>
void Test(P)
{
std::cout << "类模板,模板成员函数,一般" << std::endl;
}
/// 特化成员函数 p(int)
template <>
void Test(int)
{
std::cout << "类模板,模板成员函数,偏特化" << std::endl;
}
static int m_nData;
};
/// 模板类静态成员初始化
template<>
int TClass<int,int>::m_nData = 0;
/// 类模板偏特化 T2(int)
template <typename T1>
class TClass<T1, int>
{