C++ 专业化不起作用

C++ specialization does not working

我这个月开始学习语言 (С++)。 专业化必须return 最长的地址行。我的代码不工作。编译器错误未显示。

#include <iostream>
#include <cstring>

using namespace std;

template <typename T>
T maxn(const T * cArr, const int iSize);
template <>
char * maxn<char*>(char * const * cArr, const int iArrSize);

int main(void){

    int iTest = 0;
    double dTest = 0.0;

    int iArr[6] = {1, 2, 3, 7, 5, 6};
        int iArrSize = (sizeof(iArr))/(sizeof(iArr[0]));
    double dArr[4] = {1.0, 2.0, 3.0, 4.0};
        int dArrSize = (sizeof(dArr))/(sizeof(dArr[0]));
    const char * cNames[5] = {"Mona", "Elzushka", "Leopold", "Burger", "Arny"};
        int iSizeOf = (sizeof(cNames)) / (sizeof(cNames[0]));


    iTest = maxn(iArr, iArrSize);
        cout << "Test maxn(int) = " << iTest << endl;
    dTest = maxn(dArr, dArrSize);
        cout << "Test maxn(double) = " << dTest << endl;
    const char * cTest = maxn(cNames, iSizeOf);
        cout << "Test maxn(char) = " << cTest << endl;

    return 0;
}

template <typename T>
T maxn(const T* tArr, const int iSize)
{
    T tMax = tArr[0];

    for (int i = 0; i < iSize; i++)
    {
        if (tArr[i] > tMax){
            tMax = tArr[i];
        }
    }
    cout << "MAXN T " << endl;
    return tMax;
}

我的专长不工作。

template <>
char * maxn<char*>(char * const * cArr, const int iArrSize)
{
    char * cMaxLen = &cArr[0][0];

    for (int i = 0; i < iArrSize; i++)
    {
        if (strlen(&cArr[i][0]) > strlen(cMaxLen)){
            cMaxLen = &cArr[i][0];
        }
    }
    cout << "MAXN C " << endl;
    return cMaxLen;
}

程序来自书本"S.Prata: C++ Primer Plus"

您期待在以下行中调用 maxn

const char * cTest = maxn(cNames, iSizeOf);

决心转专业。 cNames 声明为:

const char * cNames[5] = {"Mona", "Elzushka", "Leopold", "Burger", "Arny"};

cNames 衰减到 const char**。如果您希望该调用与专业化相匹配,专业化需要是:

template <>
char const * maxn<char const*>(char const * const * cArr, const int iArrSize);

在我进行更改并更改实现以匹配它之后,我使用您发布的其余代码得到以下输出。

MAXN T
Test maxn(int) = 7
MAXN T
Test maxn(double) = 4
MAXN C
Test maxn(char) = Elzushka