dimanche 22 octobre 2023

In the function template, char * arguments cannot match explicit specialization const char * parameters

IN the book C++ Primer Plus I see a form enter image description here

and when I write my code below

#include<iostream>
#include<cstring>
using namespace std;
template<typename T>
T maxn(T arr[],int n);

template<>
const char*  maxn<const char* >(const char*arr[] ,int n);

template<>
char*  maxn<char* >(char*arr[] ,int n);

int main()
{   
    int arr1[6]={1,2,3,4,5,6};
    double arr2[4]={1.1,2.2,3.3,4.4};
    char* arr3[5]={
        "a",
        "hijkl",
        "def",
        "bc",
        "lmno",
    };
    
    cout << maxn(arr3,4) << endl;
    cin.get();
    return 0;
}
template<typename T>            //template A  general template
T maxn(T arr[],int n)
{
    T max=0;
    for(int i=0;i<n;i++)
    max = max > arr[i]?max:arr[i];
    return max;
}

template<>             //template B   explicit specialization  with const
const char*  maxn<const char* >(const char* arr[] ,int n)  
{                                                      
    const char*  pm=arr[0];                           
                                                       
    for(int i=0;i<n;i++)
    {
        if(strlen(pm)<strlen(arr[i]))
        pm=arr[i];
    }
    return pm;
}

template<>      //Template C  explicit specialization  without const
char*  maxn<char* >(char* arr[] ,int n)
{   
    char*  pm=arr[0];
    for(int i=0;i<n;i++)
    {
        if(strlen(pm)<strlen(arr[i]))
        pm=arr[i];
    }
    return pm;
}

If template a and template c are removed, the actual parameter char * will not be assigned to the const char parameter of template b, and an error message will be reported: Undefined reference to 'char maxn<char *>(char * *, int)', I understand its meaning. It says that I did not define a template like 'char * maxn<char >(char * , int)', but does not the book say that type can be converted to const type? Why not convert the char here to const char?

I think template B should be used instead error.

Aucun commentaire:

Enregistrer un commentaire