【发布时间】:2015-11-22 22:20:17
【问题描述】:
我正在编写一个程序,该程序需要一个模板函数,该函数具有一个项目数组,以及该数组中的项目数作为参数。该函数需要返回所述数组中的最大项。如果输入了字符串数组,该程序还应该有一个专门化(我遇到的问题),它检查数组中最长的字符串。
这是我的原型:
template <typename T>
T compare(T const arr1[], int n);
template <> const char *compare<const char *>(const char *const arr2[][3], int n);
主程序..
int main()
{
int a[7] = { 3, 67, 100, 91, 56, 67, 83 };
double b[] = { 2.5, 2.6102, 2.61, 1.03 };
//char* c[3] = { "see if this works", "functions", "explicit specialization" };
char c0[30] = { "see if this works" };
char c1[30] = { "functions" };
char c2[30] = { "explicit specialization" };
char *d[][3] = { c0, c1, c2 };
cout << "Comparing int values: " << endl;
cout << "Largest int value is: " << compare(a, 7) << endl;
cout << "Comparing double values: " << endl;
cout << "Largest double value is: " << compare(b, 4) << endl;
return 0;
}
函数定义...
template <typename T>
T compare(T const arr1[], int n) {
T temp;
........
return temp;
}
template <> const char *compare<const char *>(const char *const arr2[][3], int n); {
const char *temp2 = &arr2[0];
return *temp2;
}
我写了一些虚拟代码来测试第二个函数是否有效,但它没有返回正确的值(它返回“显式特化”)有人可以指出语法有什么问题吗?
【问题讨论】:
-
当你想完全特化一个模板函数时,你真正想要的是用一个非模板函数重载它。完全专业化是您对模板类而不是模板函数执行的操作。
-
谢谢。我目前正在阅读一本书的练习,其中的说明包括检查最长字符串的专业化。
标签: c++ function templates specialization