考虑下面的代码
#include <iostream>
#include <cstring>
template <int size>
void func(const char (&arr)[size])
{
//Prefer this function for const string literals.
std::cout << "Array of " << size - 1 << " bytes" << std::endl;
}
void func(const char *arr)
{
//Use this for all other strings that are not literals
std::cout << "String of " << strlen(arr) << " bytes" <<std::endl;
}
int main()
{
func("Hello!");
return 0;
}
Run Code Online (Sandbox Code Playgroud)
如何确保示例中调用的是模板函数而不是重载?
我希望模板化函数在字符串文字上调用,而另一个可用于所有其他情况。使用模板化函数,我可以避免调用 strlen()。在我的应用程序中,这两个函数最终都创建了一个 string_view 对象。
我想知道如何选择过载。
c++ ×1