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