。但并不能否定原作者是错的,这只是一个特例,看下面的示例:
类模板的默认模板类型形参示例3:
TemplateDemo03.h
1 #ifndef TEMPLATE_DEMO_03
2 #define TEMPLATE_DEMO_03
3
4 template<class T1=int,class T2,class T3> class CeilDemo{
5 public:
6 double ceil(T1,T2,T3);
7 };
8
9 template<class T1,class T2,class T3>
10 double CeilDemo<T1,T2,T3>::ceil(T1 a,T2 b,T3 c){
11 return a+b+c;
12 }
13
14 #endif
TemplateDemo03.cpp
1 #include<iostream.h>
2 #include "TemplateDemo03.h"
3
4 void main(){
5 CeilDemo<double,double> cd;
6 cout<<cd.ceil(2,3.1,4.1)<<endl;
7 }
编译错误:
1 --------------------Configuration: TemplateDemo03 - Win32 Debug--------------------
2 Compiling...
3 TemplateDemo03.cpp
4 g:\c++\cdaima\templatedemo03\templatedemo03.h(12) :
5 error C2244: 'CeilDemo<T1,T2,T3>::ceil' : unable to resolve function overload
6 g:\c++\cdaima\templatedemo03\templatedemo03.cpp(6) :
7 error C2065: 'cd' : undeclared identifier
8 g:\c++\cdaima\templatedemo03\templatedemo03.cpp(6) :
9 error C2228: left of '.ceil' must have class/struct/union type
10 Error executing cl.exe.
11
12 TemplateDemo03.obj - 3 error(s), 0 warning(s)
从上面的例子我们可以看出,当我们试图把T2和T3定义为double类型就会出现错误(T1默认定义的是int类型)。那是不是我们按照作者所说把T2和T3也设定为默认值double,是否还会出现错误?看下面的示例:
类模板的默认模板类型形参示例4:
TemplateDemo03.h
1 #ifndef TEMPLATE_DEMO_03
2 #define TEMPLATE_DEMO_03
3
4 template<class T1=int,class T2=double,class T3=double> class CeilDemo{
5 public:
6 double ceil(T1,T2,T3);
7 };
8
9 template<class T1,class T2,class T3>
10 double CeilDemo<T1,T2,T3>::ceil(T1 a,T2 b,T3 c){
11 return a+b+c;
12 }
13
14 #endif
TemplateDemo03.cpp
1 #include<iostream.h>
2 #include "TemplateDemo03.h"
3
4 void main(){
5 CeilDemo<int,double,double> cd;
6 cout<<cd.ceil(2,3.1,4.1)<<endl;
7 }
编译错误:
--------------------Configuration: TemplateDemo03 - Win32 Debug--------------------
Compiling...
TemplateDemo03.cpp
g:\c++\cdaima\templatedemo03\templatedemo03.h(12) :
error C2244: 'CeilDemo<T1,T2,T3>::ceil' : unable to resolve function overload
g:\c++\cdaima\templatedemo03\templatedemo03.cpp(6) :
error C2065: 'cd' : undeclared identifier
g:\c++\cdaima\templatedemo03\templatedemo03.cpp(6) :
error C2228: left of '.ceil' must have class/struct/union type
Error executing cl.exe.
TemplateDemo03.obj - 3 error(s), 0 warning(s)
从结果我们可以看出,和上例是一样的错误。从实例中我们可以总结如下:类模板如果有多个类型形参,如果使用类型形参默认值则尽量放在参数列表的末尾,而且默认的参数类型必须相同。如果从第一个形参设定了默认值之后的所有模板形参都要设定和第一个形参同类型的默认值。(声明:本人也是刚接触C++,以上只是我经过实例演示对原作者提出的一些质疑,可能我的示例有不到之处,还望大神们不吝赐教,共同完善此博客,给像我一样的菜鸟提供一个学习的平台!)
接下来验证“不能为函数模板的类型形参提供默认值”:
类模板的默认模板类型形参示例5:
TemplateDemo04.cpp
1 #include<iostream.h>
2
3 template<class T1,class T2,class T3>
4 T1 sum(T1 a,T2 b,T3 c=int){
5 return a+b+c;
6 }
7
8 void main(){
9 cout<<sum<double,double>(1.1,2.1,3)<<endl;
10 }
编译错误:
1 --------------------Configuration: TemplateDemo04 - Win32 Debug--------------------
2 Compiling...
3 TemplateDemo04.cpp
4 g:\c++\cdaima\templatedemo04\templatedemo04.cpp(4) :
5 error C2062: type 'int' unexpected
6 Error executi