Chinaunix

标题: 模板高手请进 [打印本页]

作者: yuonunix    时间: 2007-11-12 14:34
标题: 模板高手请进
//: C05:ImplicitCast.cpp
// From "Thinking in C++, Volume 2", by Bruce Eckel & Chuck Allison.
// (c) 1995-2004 MindView, Inc. All Rights Reserved.
// See source code use permissions stated in the file 'License.txt',
// distributed with the code package available at www.MindView.net.
template<typename R, typename P>
R implicit_cast(const P& p) {
  return p;
}
int main() {
  int i = 1;
  float x = implicit_cast<float>(i);
  int j = implicit_cast<int>(x);
  //! char* p = implicit_cast<char*>(i);
} ///:~

书中说:
如果将程序中,靠近文件顶部的模板参数列表中的R 和P交换一下,这个程序将不能通过编译,这是因为没有指定函数的返回类型(第1个模板参数将作为函数的参数类型)

发现确实如此,交换R和P就编译不过,不过看不懂为什么,请指教一下?
作者: vincol    时间: 2007-11-12 17:30
对啊,  
float x = implicit_cast<float>(i);
调用
template<typename R, typename P>
R implicit_cast(const P& p) {
  return p;
}
制指定了R为float,如果把模板参数列表中的R和P交换的话,必须把R implicit_cast(const P& p)中的R和P也交换,否则返回类型不明!




欢迎光临 Chinaunix (http://bbs.chinaunix.net/) Powered by Discuz! X3.2