您好,登錄后才能下訂單哦!
本篇文章為大家展示了C++模板使用方法是什么,內(nèi)容簡(jiǎn)明扼要并且容易理解,絕對(duì)能使你眼前一亮,通過(guò)這篇文章的詳細(xì)介紹希望你能有所收獲。
C++編程語(yǔ)言中的模板應(yīng)用在一定程度上大大提高了程序開(kāi)發(fā)的效率。我們?yōu)榇蠹以敿?xì)講解一下有關(guān)C++模板的基本概念。
前段時(shí)間重新學(xué)習(xí)C++,主要看C++編程思想和C++設(shè)計(jì)新思維。對(duì)模版的使用有了更進(jìn)一層的了解,特總結(jié)如下:
下面列出了C++模板的常用情況:
1. C++模板類(lèi)靜態(tài)成員
template < typename T> struct testClass { static int _data; }; template< > int testClass< char>::_data = 1; template< > int testClass< long>::_data = 2; int main( void ) { cout < < boolalpha < < (1==testClass< char>::_data) < < endl; cout < < boolalpha < < (2==testClass< long>::_data) < < endl; }
2. C++模板類(lèi)偏特化
template < class I, class O> struct testClass { testClass() { cout < < "I, O" < < endl; } }; template < class T> struct testClass< T*, T*> { testClass() { cout < < "T*, T*" < < endl; } }; template < class T> struct testClass< const T*, T*> { testClass() { cout < < "const T*, T*" < < endl; } }; int main( void ) { testClass< int, char> obj1; testClass< int*, int*> obj2; testClass< const int*, int*> obj3; }
3.類(lèi)模版+函數(shù)模版
template < class T> struct testClass
{
void swap( testClass< T>& ) { cout < < "swap()" < < endl; }
};
template < class T> inline void swap( testClass< T>& x,
testClass< T>& y ){
x.swap( y );
}
int main( void )
{
testClass< int> obj1;
testClass< int> obj2;
swap( obj1, obj2 );
}
4. 類(lèi)成員函數(shù)模板
struct testClass { template < class T> void mfun( const T& t ) { cout < < t < < endl; } template < class T> operator T() { return T(); } }; int main( void ) { testClass obj; obj.mfun( 1 ); int i = obj; cout < < i < < endl; }
5. 缺省C++模板參數(shù)推導(dǎo)
template < class T> struct test { T a; }; template < class I, class O=test< I> > struct testClass { I b; O c; }; void main() { }
6. 非類(lèi)型C++模板參數(shù)
template < class T, int n> struct testClass { T _t; testClass() : _t(n) { } }; int main( void ) { testClass< int,1> obj1; testClass< int,2> obj2; }
7. 空模板參數(shù)
template < class T> struct testClass;
template < class T> bool operator==( const testClass< T>&,
const testClass< T>& ){
return false;
};
template < class T> struct testClass
{
friend bool operator== < >
( const testClass&, const testClass& );};
void main()
{
}
8. template template 類(lèi)
struct Widget1 { template< typename T> T foo(){} }; template< template< class T>class X> struct Widget2 { }; void main() { cout< < 3 < < '\n'; }
上述內(nèi)容就是C++模板使用方法是什么,你們學(xué)到知識(shí)或技能了嗎?如果還想學(xué)到更多技能或者豐富自己的知識(shí)儲(chǔ)備,歡迎關(guān)注億速云行業(yè)資訊頻道。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。