[英]template function taking array argument vs overload function taking pointer argument
考虑以下代码
#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;
}
如何确保在示例中调用模板 function 而不是重载?
我希望模板化的 function 在字符串文字上被调用,而另一个可用于所有其他情况。 使用模板化的 function,我可以避免调用 strlen()。 在我的应用程序中,这两个函数最终都创建了一个 string_view object。
我想知道如何优先选择过载。
问题在于,在重载解析期间对标准转换序列进行排名时,数组到指针的转换算作精确匹配排名。 由于数组重载是模板,因此指针重载成为更好的匹配。
您可以为指针重载添加一个代理 object,以在参数的类型为const char (&)[N]
时强制它进入比数组重载更糟糕的转换序列:
namespace detail {
struct Proxy {
Proxy(const char *ptr) : ptr_{ptr} {};
operator const char *() const { return ptr_; }
private:
const char *ptr_;
};
} // namespace detail
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(detail::Proxy const &proxy) {
// Use this for all other strings that are not literals
std::cout << "String of " << strlen(proxy) << " bytes" << std::endl;
}
int main() {
func("Hello!"); // Array of 6 bytes
const char *str = "Hello!";
func(str); // String of 6 bytes
}
带有引用的技巧使常规 function 与const char*
不完全匹配。
#include <iostream>
#include <cstring>
template <size_t 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!");
const char *s = "s";
func(s);
return 0;
}
Output
Array of 6 bytes
String of 1 bytes
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.