C++编程语言中的模板应用在一定程度上大大提高了程序开发的效率。我们在这篇文章中为大家详细讲解一下有关C++模板的基本概念,希望初学者们可以通过本文介绍的内容充分掌握这方面的知识。
10年专注成都网站制作,成都企业网站建设,个人网站制作服务,为大家分享网站制作知识、方案,网站设计流程、步骤,成功服务上千家企业。为您提供网站建设,网站制作,网页设计及定制高端网站建设服务,专注于成都企业网站建设,高端网页制作,对成都小搅拌车等多个方面,拥有丰富的网站维护经验。
前段时间重新学习C++,主要看C++编程思想和C++设计新思维。对模版的使用有了更进一层的了解,特总结如下:
下面列出了C++模板的常用情况:
1. C++模板类静态成员
- 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++模板类偏特化
- 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.类模版+函数模版
- 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. 类成员函数模板
- 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++模板参数推导
- template < class T> struct test
- {
- T a;
- };
- template < class I, class O=test< I> > struct testClass
- {
- I b;
- O c;
- };
- void main()
- {
- }
6. 非类型C++模板参数
- template < class T, int n> struct testClass {
- T _t;
- testClass() : _t(n) {
- }
- };
- int main( void ) {
- testClass< int,1> obj1;
- testClass< int,2> obj2;
- }
7. 空模板参数
- 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 类
- struct Widget1
- {
- template< typename T>
- T foo(){}
- };
- template< template< class T>class X>
- struct Widget2
- {
- };
- void main()
- {
- cout< < 3 < < '\n';
- }
以上就是对C++模板的一些常用方法的介绍。
名称栏目:C++模板常用使用方法介绍
转载注明:http://www.csdahua.cn/qtweb/news39/88389.html
网站建设、网络推广公司-快上网,是专注品牌与效果的网站制作,网络营销seo公司;服务项目有等
声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 快上网