A problem with Function Template Specialization

I'm trying to do a specialization to a const function template, but i obtain this:

C:\proyectos3\Capitulo 8\EX6\main.cpp|11|error: template-id 'maxn<>' for 'const char* maxn(const char**, int)' does not match any template declaration|

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
//TEMPLATE PROTOTYPE
template<typename T>
const T * maxn(const T * arr, int n);

// SPECIALIZATION PROTOTYPE
template <> const char * maxn(const char ** arr, int n);

// TEMPLATE DEFINITION
template<typename T>
const T * maxn(const T * arr, int n)
{
    if(n <= 0)
        return nullptr;

    const T * mayor = &arr[0];

    for(int i=1; i<n; i++)
    {
        if(arr[i] > *mayor)
            mayor = &arr[i];
    }

    return mayor;
}

// SPECIALIZATION TEMPLATE DEFINITION
template <> const char * maxn<char *> (const char *arr[] , int n)
{
    cout << "SIIIIIIIII" << endl;
    if(n <= 0)
        return false;

    const char * mayor = arr[0];
    int sMayor;
    for(sMayor = 0; arr[0][sMayor] != '\0'; sMayor++);

    int sActual = 0;
    for(int i=1; i<n; i++)
    {
        for(sActual = 0; arr[i][sActual] != '\0'; sActual++);
        if(sActual > sMayor)
        {
            mayor = arr[i];
            sMayor = sActual;
        }
    }

    return mayor;
}
Last edited on
If you must specialise the function template template <typename T> const T* maxn( const T* arr, int n );,
the specialisation must have the same signature as the base template, with type parameter T being substituted with the type in the specialisation.

For example, this is fine:
1
2
3
4
5
6
7
8
9
10
11
//TEMPLATE PROTOTYPE
template <typename T> const T* maxn( const T* arr, int n );

// SPECIALIZATION PROTOTYPE
// 'T' in the base template <=> 'const char*' in the specialisation
using pcchar = const char* ; 
template <> const pcchar* maxn( const pcchar* arr, int n);

// redeclaration of the specialisation: same as above
// 'T' in the base template <=> 'const char*' in the specialisation
template <> const char* const* maxn( const char* const* arr, int n );


In general, if you want to customise a function template, overload the function; do not specialise it.
This works intuitively: the overload participates in normal overload resolution.

For instance:
1
2
3
4
5
// function template
template <typename T> const T* maxn( const T* arr, int n );

// overload maxn (do not specialise)
const char * maxn(const char ** arr, int n);


More information: 'Why Not Specialize Function Templates?' http://www.gotw.ca/publications/mill17.htm
Thank you very much JLBorges for your repply, you have helped a lot :D
Last edited on
Topic archived. No new replies allowed.