Templates and Default Arguments

本文探讨了C++模板中默认参数的使用方法及规则,通过实例展示了如何为模板参数设置默认值,并强调了参数默认值设置的顺序规则。

 

 

  Default parameters for templates in C++:
  Like function default arguments, templates can also have default arguments. For example, in the following program, the second parameter U has the default value as char.

 1 #include<iostream>
 2 using namespace std;
 3 
 4 template<class T, class U = char> class A
 5 {
 6 public:
 7     T x;
 8     U y;
 9 };
10 
11 int main()
12 {
13     A<char> a;
14     A<int, int> b;
15     cout<<sizeof(a)<<endl;
16     cout<<sizeof(b)<<endl;
17     return 0;
18 }

  Output: (char takes 1 byte and int takes 4 bytes)
  2
  8

  Also, similar to default function arguments, if one template parameter has a default argument, then all template parameters following it must also have default arguments.

  For example, the compiler will not allow the following program:

 1 #include<iostream>
 2 using namespace std;
 3  
 4 template<class T = char, class U, class V = int> class A  // Error
 5 { 
 6    // members of A
 7 };
 8  
 9 int main()
10 {
11    
12 } 

   template的默认参数列表规则与函数的默认参数列表规则一样。

 

 

  Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
  

  转载请注明:http://www.cnblogs.com/iloveyouforever/

  2013-11-26  22:21:23

转载于:https://www.cnblogs.com/iloveyouforever/p/3444433.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值