0

I began to learn the language (С++) this month. Specialization must return the address of the longest line. My code is not working. The compiler errors are not showing.

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

My specialization is not working.

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

The program is from the book "S.Prata: C++ Primer Plus"

Rohit Gupta
  • 4,022
  • 20
  • 31
  • 41
Kas Elvirov
  • 7,394
  • 4
  • 40
  • 62

1 Answers1

1

You are expecting the call to maxn in the following line:

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

to resolve to the specialization. cNames is declared as:

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

cNames decays to const char**. If you want that call to match the specialization, the specialization needs to be:

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

After I made that change and changed the implementation to match it, I get the following output using rest of your posted code.

MAXN T
Test maxn(int) = 7
MAXN T
Test maxn(double) = 4
MAXN C
Test maxn(char) = Elzushka
R Sahu
  • 204,454
  • 14
  • 159
  • 270