Chinaunix首页 | 论坛 | 博客
  • 博客访问: 8053553
  • 博文数量: 594
  • 博客积分: 13065
  • 博客等级: 上将
  • 技术积分: 10324
  • 用 户 组: 普通用户
  • 注册时间: 2008-03-26 16:44
个人简介

推荐: blog.csdn.net/aquester https://github.com/eyjian https://www.cnblogs.com/aquester http://blog.chinaunix.net/uid/20682147.html

文章分类

全部博文(594)

分类: C/C++

2015-10-20 17:45:53

设计一函数f(),使用得下面代码中的第一个f()调用可正常编译,而其它编译报错
  1. #include <stdio.h>
  2. #include <string>
  3. int main()
  4. {
  5.     f("hello"); // 正常编译通过
  6.     
  7.     const char* str1 = "hello";
  8.     f(str1); // 编译报错: no matching function for call to
  9.     
  10.     std::string str2 = "hello";
  11.     f(str2); // 编译报错: no matching function for call to

  12.     return 0;
  13. }

满足上述目标的f()函数实现:
  1. template <size_t N>
  2. void f(const char (&str)[N])
  3. {
  4.     printf("%s\n", str);
  5. }

代码中的f("hello")调用的函数真实原型为:
  1. void f(const char (&str)[6]);

也可以写成下面这样容易看的:
  1. typedef char X[6];
  2. void f(const X& str);








阅读(2457) | 评论(0) | 转发(0) |
0

上一篇:arean.c

下一篇:CMake使用技巧集

给主人留下些什么吧!~~