现在的位置: 首页 > 综合 > 正文

2.2Argument Deduction

2013年10月01日 ⁄ 综合 ⁄ 共 723字 ⁄ 字号 评论关闭
原来将template的参数实例化就是argument deduction。前一段时间在使用template的时候,遇到了编译器的错误,当时不知所云。要是早看到这篇文章的话就会好很多啦。
看2.2节有这样的问题
template <typename T> 
inline T const& max (T const& a, T const& b);

max(4,7) // OK: T is int for both arguments
max(4,4.2) // ERROR: first T is int, second T is double

原来第二种的话,我觉得问题有可能是让编译器不知所云吧。因为编译器不知道是将整型转为double还是将double
转为整型。
这也就说明,写程序的时候,尽量不要做这种二义性的代码。我记得Effective C++上也有过这样的例子。
当时好像是说0这个东东,既可能是作为int,也可能作为指针。得回去温习一下了。

解决上面问题的方法
  1. Cast the arguments so that they both match: 将其中一个参数转化,使之类型一样

    max(static_cast<double>(4),4.2)    // OK 

  2. Specify (or qualify) explicitly the type of T: 强制性地声明T的类型,这种我没想到。

    max<double>(4,4.2)                 // OK 

  3. Specify that the parameters may have different types. 这个比较简单,就是在声明的时候就表示这两个参数是不同类型的

这也是表现出来template对类型的检查原来是非常严格的。我在编程的时候就不太注重int, long, double
这些built-in type的区别,这不是好习惯。

抱歉!评论已关闭.