Search code examples
c++c++11templatesspecializationexplicit

Explicit specialization - template-id does not match any template declaration


I have a problem regarding explicit specialization in C++ program

I want to make a specialization for char* type that returns an address to the longest char array but i keep getting errors :

C:\Users\Olek\C++\8_1\main.cpp|6|error: template-id 'maxn<char*>' for 'char* maxn(char*)' does not match any template declaration|
C:\Users\Olek\C++\8_1\main.cpp|38|error: template-id 'maxn<char*>' for 'char* maxn(char*)' does not match any template declaration|

Here is the code to the program

#include <iostream>

template <typename T>
T maxn(T*,int);

template <> char* maxn<char*>(char*);

const char* arr[5]={
    "Witam Panstwa!",
    "Jak tam dzionek?",
    "Bo u mnie dobrze",
    "Bardzo lubie jesc slodkie desery",
    "Chociaz nie powinienem",
};

using namespace std;

int main()
{
    int x[5]={1,4,6,2,-6};
    double Y[4]={0.1,38.23,0.0,24.8};
    cout<<maxn(x,5)<<endl;
    cout<<maxn(Y,4)<<endl;
    return 0;
}

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

template <>
char* maxn<char*>(char* ch){
    return ch;
}

I haven't implemented the function yet but it has been declared. Also i suppose that it would be easier to use function overload but it is an assigment from a book.

Thanks for answers in advance.


Solution

  • Your template returns the type T and takes a type T* but your specialization returns the same type as it takes, so it doesn't match.

    If you specialize for T=char*, then it needs to take a T* (char**) and return a char* or instead specialize on char

    template <typename T>
    T maxn(T*,int);
    
    template <> char maxn<char>(char*, int);
    template <> char* maxn<char*>(char**, int);
    
    int main() {
        char * str;
        maxn(str, 5);
        maxn(&str, 6);
    }