设计一函数f(),使用得下面代码中的第一个f()调用可正常编译,而其它编译报错
满足上述目标的f()函数实现:
代码中的f("hello")调用的函数真实原型为:
也可以写成下面这样容易看的:
- #include stdio.h>
- #include string>
- int main()
- {
- f("hello"); // 正常编译通过
-
- const char* str1 = "hello";
- f(str1); // 编译报错: no matching function for call to
-
- std::string str2 = "hello";
- f(str2); // 编译报错: no matching function for call to
-
- return 0;
- }
满足上述目标的f()函数实现:
- template size_t N>
- void f(const char (&str)[N])
- {
- printf("%s\n", str);
- }
代码中的f("hello")调用的函数真实原型为:
- void f(const char (&str)[6]);
也可以写成下面这样容易看的:
- typedef char X[6];
- void f(const X& str);