C++模板簡(jiǎn)單分析與舉例
#pragma once
#include <iostream>
/*/////////////////////////////////////////////
C++ 模板 
/////////////////////////////////////////////*/

/*
--- 函數(shù)模板 ---
*/
/// 聲明
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;
}
/// 重載,函數(shù)的參數(shù)個(gè)數(shù)不同
template <typename T1>
void TFunc(T1)
{
std::cout << "重載" << std::endl;
}
/// 函數(shù)模板不允許默認(rèn)的參數(shù)類型,而類模板允許
// template <typename T1, typename T2=int>
// void DefaultParamFun(T1, T2){}
/// 測(cè)試模板函數(shù)
void Test_Func()
{
TFunc<int,int>(0, 0); // 一般
TFunc<char>('a', 0); // 偏特化
TFunc('a','a'); // 全特化
TFunc<int>(0); // 重載
std::cout << std::endl;
}

/*
--- 類模板 ---
*/
/// 類模板允許默認(rèn)的參數(shù)類型
template <typename T1, typename T2=int>
class TClass
{
public:
TClass()
{
std::cout << "類模板,一般" << std::endl;
} 
template <typename P>
void Test(P)
{
std::cout << "類模板,模板成員函數(shù),一般" << std::endl;
}
/// 特化成員函數(shù) p(int)
template <>
void Test(int)
{
std::cout << "類模板,模板成員函數(shù),偏特化" << std::endl;
}
static int m_nData;
}; 
/// 模板類靜態(tài)成員初始化
template<>
int TClass<int,int>::m_nData = 0;
/// 類模板偏特化 T2(int)
template <typename T1>
class TClass<T1, int>
{
public:
TClass()
{
std::cout << "類模板,偏特化" << std::endl;
}
};
/// 類的成員函數(shù)模板
class TMemFun
{
public:
template <typename T>
void Test(T)
{
std::cout << "類的成員函數(shù)模板" << std::endl;
}
};
/// 測(cè)試模板類
void Test_Class()
{
TClass<bool,char> tClass1;
tClass1.Test('a'); // 模板成員函數(shù),一般
tClass1.Test(0); // 模板成員函數(shù),偏特化
TClass<bool,int> tClass2; // 類偏特化
TMemFun tMemFun;
tMemFun.Test(1); // 類的成員函數(shù)模板
std::cout << std::endl;
}

/*
--- 類型自動(dòng)轉(zhuǎn)換 ---
1、數(shù)組與指針互轉(zhuǎn)
2、限制修飾符const與非const互轉(zhuǎn)
*/
/// 參數(shù)為指針
template <typename T>
void PtrFun(T*){}
/// 參數(shù)為數(shù)組
template <typename T>
void ArrayFun(T[]){} 
/// const參數(shù)
template <typename T>
void ConstFun(const T){}
/// 非const參數(shù)
template <typename T>
void UnConstFun(T){} 
class CBase{}; // 父類
class CDerived : public CBase{}; // 子類
template <typename T>
void ClassFun(T){}
void Test_TypeConversion()
{
int nValue = 1;
ConstFun(nValue); // 非const --> const
const int cnValue = 1;
UnConstFun(cnValue); // const --> 非const
int nArray[2] = {0,0};
PtrFun(nArray); // 數(shù)組 --> 指針
int* pInt = NULL;
ArrayFun(pInt); // 指針 --> 數(shù)組
CDerived derived;
ClassFun<CBase>(derived); // 子類 --> 父類
// CBase base;
// ClassFun<CDerived>(base); // 不允許,父類 --> 子類
}
void Test_Template()
{
Test_Func();
Test_Class();
Test_TypeConversion();
}
posted on 2013-03-30 14:23 chenjt3533 閱讀(355) 評(píng)論(0) 編輯 收藏 引用 所屬分類: C/C++



