【问题标题】:explicit specialization: syntax error?显式专业化:语法错误?
【发布时间】: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


【解决方案1】:

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

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

【讨论】:

  • 谢谢!我明白你关于字符串序列的观点。我目前正在练习我的书,说明是使用指针到字符和指针数量,但不太确定如何在专用函数上使用它(也是练习的要求?)
猜你喜欢
  • 2018-09-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-12-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多