error in template function when i even didn't use it

67 Views Asked by At
#include <iostream>
#include <string>
#include <typeinfo>
using namespace std;

template<class T>
T maxn(T* a,int n);

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

int main()
{
//    int n6[6]{21,56,89,49,258,41};
//    double n4[4]{2.1,5.6,8.9,4.9};
//    auto m=maxn(n6,6);
//    auto n=maxn(n4,4);
//    cout<<m<<endl;
//    cout<<n<<endl;
    const char* words[3]={"one","two","three"};
//    maxn(words,3);
    return 0;
}

template<> void maxn(const char* s[],int n)
{
    cout<<"ok";
}

template<class T>
T maxn(T* a,int n)
{
    T max=a[0];
    for (int i=1;i<n;i++)
    {
        if (a[i]>max)
        {
            max=a[i];
        }
    }
    return max;
}

I want to write an explicit specialization of maxn() that passes a char*[] array as a parameter, but it reports the following error when I don't even call the function:

[Error] template-id 'maxn<>' for 'void maxn(const char**, int)' does not match any template declaration

[Note] candidate is: 'template<class T> T maxn(T*, int)'

2

There are 2 best solutions below

5
Quimby On

The specialization must take a T* and return a T. Your specialization returns void, that is not correct.

Either return T like this:

#include <iostream>
#include <string>

using namespace std;

template<class T>
T maxn(T* a,int n);

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

int main()
{
    const char* words[3]={"one","two","three"};
    return 0;
}

template<> const char* maxn(const char* s[],int n)
{
    cout<<"ok";
    return nullptr; // Fix this
}

template<class T>
T maxn(T* a,int n)
{
    T max=a[0];
    for (int i=1;i<n;i++)
    {
        if (a[i]>max)
        {
            max=a[i];
        }
    }
    return max;
}

Or define the primary template like this:

template<class T,class Ret>
Ret maxn(T* a,int n);
4
user12002570 On

Since we can just overload function templates with ordinary non-template function, there is no need to provide an explicit specialization for the function template as shown below.

Looking at your code(the return type and argument type in the explicit specialization in particular), it seems this is what you were looking for.

template<class T>
T maxn(T* a,int n);

//removed template<> from here so that this becomes a non-template function
void maxn(const char* s[],int n)
{
    cout<<"ok";
}
 
template<class T>
T maxn(T* a,int n)
{
    T max=a[0];
    for (int i=1;i<n;i++)
    {
        if (a[i]>max)
        {
            max=a[i];
        }
    }
    return max;
}
int main()
{

    const char* words[3]={"one","two","three"};
    maxn(words,3);//works now
}

Working demo