C++隨筆 之 函數(shù)模板(Function Template)1 (原創(chuàng))
1.Function Template可以針對(duì)不同的Template arguments完成一個(gè)系列的函數(shù)
例如
template<typename T>
inline T const & max(T const &a,T const &b)
{
???return???a>b?a:b;
}
2.Function template可以從傳遞過(guò)來(lái)的arguments的類(lèi)型來(lái)具體化
int a = ::max(10,20);
那么Function template 就具體化為
inline int const& max(int const &a,int const & b)
3.你可以具體指出它的參數(shù)類(lèi)型
int a = ::max<int>(10,20);
4.Function template可以被重載overloaded
inline T const& max(T const &a,T const &b,T const &c)
{
???return ::max(::max(a,b),c);
}
當(dāng)然記住一點(diǎn),重載的相似點(diǎn)越小越好
例如
template<typename T>
inline T const & max(T const &a,T const &b)
{
???return???a>b?a:b;
}
2.Function template可以從傳遞過(guò)來(lái)的arguments的類(lèi)型來(lái)具體化
int a = ::max(10,20);
那么Function template 就具體化為
inline int const& max(int const &a,int const & b)
3.你可以具體指出它的參數(shù)類(lèi)型
int a = ::max<int>(10,20);
4.Function template可以被重載overloaded
inline T const& max(T const &a,T const &b,T const &c)
{
???return ::max(::max(a,b),c);
}
當(dāng)然記住一點(diǎn),重載的相似點(diǎn)越小越好
posted on 2007-01-10 14:36 木木頭 閱讀(401) 評(píng)論(0) 編輯 收藏 引用 所屬分類(lèi): C++特性