【发布时间】:2020-12-23 21:32:55
【问题描述】:
您好,我有来自 C++ 入门第 5 版的代码:
主函数模板:
// first version; can compare any two types
template <typename T>
int compare(T const& x, T const& y)
{
std::cout << "compare(T const&, T const&)\n";
if(std::less<T>()(x, y))
return -1;
if(std::less<T>()(y, x))
return 1;
return 0;
}
字符数组的特化:
// second version to handle string literals
template <unsigned N, unsigned M>
int compare(char const(&ar1)[N], char const(&ar2)[M])
{
std::cout << "compare(char const(&)[N], char const(&)[M])\n";
return strcmp(ar1, ar2);
}
// special version of compare to handle pointers to character arrays
template <>
int compare(const char* const &p1, const char* const &p2)
{
std::cout << "compare(char const* const&, char const* const&)\n";
return strcmp(p1, p2);
}
int main()
{
const char *p1 = "hi", *p2 = "mom";
compare(p1, p2); // calls the third version (pointers to character strings)
compare("hi", "mom"); // calls the template with two nontype parameters
compare("high", "HIGH"); // error: call ambiguous
std::cout << "\nDone!\n";
}
-
我有一些问题:
-
引用数组参数的
compare的版本是specialization还是overload?我认为它是一种特化,因为它的参数列表必须与主函数模板compare匹配。对吗? -
在我传递两个字符数组或两个长度相同的文字字符串之前,程序运行良好。在这种情况下,编译器无法像我的调用
compare("high", "HIGH");那样解析调用。:
这是否意味着它失败是因为带有数组参数的版本不可行? -因为我猜数组的大小是其类型的一部分,因此传递两个不同大小的数组会产生两种不同的类型,因此这个版本不可行?
我的编译器的输出:
error: call of overloaded ‘compare(const char [5], const char [5])’ is ambiguous
candidate: ‘int compare(const T&, const T&) [with T = char [5]]’|
candidate: ‘int compare(const char (&)[N], const char (&)[M]) [with unsigned int N = 5; unsigned int M = 5]’
- 那么我怎样才能消除这个呼叫的歧义呢?并请指导我的猜测。谢谢
【问题讨论】:
标签: c++ template-specialization function-templates