免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 1264 | 回复: 1
打印 上一主题 下一主题

模板高手请进 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 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就编译不过,不过看不懂为什么,请指教一下?

论坛徽章:
0
2 [报告]
发表于 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也交换,否则返回类型不明!
  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP