模板中实参的演绎

模板中实参的演绎

 1  //  C2782b.cpp
 2  //  compile with: /clr
 3  generic < typename T >   void  gf(T, T) { }
 4 
 5  int  main() {
 6     gf( 1 ' c ' );  //  C2782
 7      //  try the following line instead
 8      //  gf<int>(1, 'c');
 9  }
10 

模板中实参的演绎


可以先看看下面一段使用模板的代码:

 1 template  < typename T >
 2  inline T  const &  max(T  const &  a,T  const &  b) {
 3              return  a < b ? b:a;
 4             }

 5
 6 #include  < iostream >
 7 #include  < string >
 8 using   namespace  std;
 9 int  main() {
10      // -------------------正确---------
11      int  i = 42 ;
12     cout << " Max(7,i) " << ::max( 7 ,i) << endl;
13
14      double  f1 = 3.4 ;
15      double  f2 =- 6.7 ;
16     cout << " Max(f1,f2): " << ::max(f1,f2) << endl;
17
18      string  s1 = " abcd " ;
19      string  s2 = " bacd " ;
20     cout << " max(s1,s2): " << ::max(s1,s2) << endl;
21
22      // -------------------有问题--------
23     cout << ::max( 1 , 1.2 ) << endl;  // 这句会出错
24     }

25

VC2005 EE编译的时候,出现错误,错误码是C2782,可以在附带的帮助中

查看这个错误码。

  可以看到错误信息是:

    Error Message

'declaration' : template parameter 'identifier' is ambiguous

The compiler cannot determine the type of a template argument.

 

   这意思是说申明的模板参数标识符是有二义性的,编译器无法决定模板参数的类型。

   顺便附带上帮助中给的例子如下:

 1  //  C2782.cpp
 2  template < typename T >
 3  void  f(T, T) {}
 4 
 5  int  main() {
 6  f( 1 ' c ' );    //  C2782
 7  //  try the following line instead
 8  //  f<int>(1, 'c');
 9  }
10 


解决方法:
 

出现2782错误的,那么我们怎么解决呢?

可以用下面三种方法,

方法一:对实参进行强制类型转换,让他们可以互相匹配

1 max(static_cast < double > ( 1 ), 1.2 )

方法二:显示的指出T的类型

max < double > ( 1 , 1.2 )

方法三:可以指定两个参数可以具有不同的类型

那么上面的模板例子可以改写成下面这样的

1 template  < typename T1,typename T2, >
2  inline T1 max(T1  const &  a,T2  const &  b) {
3                return a<b?b:a;
4                }

5

上面这样定义模板,就可以传递不同的参数,但是这样做就必须要定义好返回类型,就是上面的T1,这是此方法的缺点。除此之外,因为两个参数类型不一样,在进行返回的时候,会在把参数b转化成T1类型的时候自动创建一个新的局部变量,这样就不可以用引用了,只能返回T1,而不是T1 const&

 

为了解决只能返回 T1 T2 两种类型之一的问题,我们可以另外再加上一个额外的类型,暂且我们给他命名为 returnType ,那么新的模板如下:
1 template  <  typename returnType,typename T1,typename T2, >
2  inline returnType max(T1  const &  a,T2  const &  b) {
3                return a<b?b:a;
4                }

5

这种方式的时候,要使用max方法就需要指定returnType的类型,

max<int,int,double>(1,1.2),因为在我们这个例子里面,returnType是在第一位置,后面两个类型是可以根据输入参数类型自动演绎(就用这个词把,书上是这么叫的)的,所以我们可以只指定一个,就是返回的类型,那么我们就可以这样写了max<int>(1,1.2).


以上就是模板中参数的演绎以及出现问题的基本的解决方法.

  以上部分来源于阅读《C++Templates 中文版》


你可能感兴趣的:(模板中实参的演绎)