编译期强制函数参数为字符串常量

2560阅读 0评论2015-10-20 aquester
分类:C/C++

设计一函数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);








上一篇:arean.c
下一篇:CMake使用技巧集