設計一函數f(),使用得下面代碼中的第一個f()調用可正常編譯,而其它編譯報錯
#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);