c++ - 显式特化 : syntax error?

标签 c++ function templates specialization

我正在编写一个程序,该程序需要一个模板函数,该函数具有一个项目数组,以及该数组中的项目数作为参数。该函数需要返回所述数组中的最大项。该程序还应该有一个专门化(我遇到的问题),如果输入了一个字符串数组,它会检查数组中最长的字符串。

这是我的原型(prototype):

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;
}

我写了一些虚拟代码来测试第二个函数是否有效,但它没有返回正确的值(它返回“显式特化”)有人可以指出语法有什么问题吗?

最佳答案

如上所述,重载比特化更适合这个问题:

const char *compare(const char *const arr2[], int n);

请注意,虽然我将方括号放入参数类型以匹配模板,但此声明等同于使用 const char *const *arr2 的声明,因为函数参数在这方面很特殊。


假设您出于任何原因绝对需要特化(尽管解释也适用于上述解决方案):

考虑什么是 T 以及您的专长是什么。 T 是序列的元素类型,您已将模板专门化为 T=char。这意味着您已将模板专门用于字符序列,而不是字符串序列。

要专用于 C 字符串序列,请将 const char * 替换为 T 而不是 char:

template <> const char *compare<const char *>(const char *const arr2[], int n);

关于c++ - 显式特化 : syntax error?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33860944/

相关文章:

wpf - 如何修复圆角按钮中边框和背景之间的空白区域?

python - Flask api 中的自定义静态路径?

c++ - 使用 C++ 等效的 memmove 向右移动数组元素

c++ - 查找多维数组的大小

c++ - 两个带参数包的函数的重载解析

python - 尝试在运行时在另一个函数内创建仅具有位置参数的函数后,会引发系统错误

c++ - C++11 中的通用 STL 兼容直方图

c++ - QT 中继承自 QWindow 的另一个类的 Resize 事件

python - 计算函数中的元音

c++ - 为什么这个随机生成器不起作用?