Search code examples
c++functiontemplatesfunction-templates

Function Template Specialization Error


I am trying to specialize my function template for list of int pointers.

template <typename typ>
void sortowanie(typ *tablica, int rozmiar, Komparator<typ> *komparator)
{
    int p;
    for(int j = rozmiar - 1; j > 0; j--)
    {
        p = 1;
        for(int i = 0; i < j; i++)
            if(komparator->porownaj(tablica[i], tablica[i + 1]))
            {
                typ pom = tablica[i];
                tablica[i] = tablica[i + 1];
                tablica[i + 1] = pom;
                p = 0;
            }
        if(p) break;
    }
};

template<>
void sortowanie<int *>(int **tablica, int rozmiar, Komparator<int> *komparator)
{
    int p;
    for(int j = rozmiar - 1; j > 0; j--)
    {
        p = 1;
        for(int i = 0; i < j; i++)
            if(komparator->porownaj(*tablica[i], *tablica[i + 1]))
            {
                int *pom = tablica[i];
                tablica[i] = tablica[i + 1];
                tablica[i + 1] = pom;
                p = 0;
            }
        if(p) break;
    }
};

But I get the following errors:

obliczenia.cpp:43:10: error: template-id ‘sortowanie<int*>’ for ‘void obliczenia::sortowanie(int**, int, Komparator<int>*)’ does not match any template declaration
void sortowanie<int*>(int* * tablica, int rozmiar, Komparator<int> *komparator) {
              ^
obliczenia.cpp:43:10: error: template-id ‘sortowanie<int*>’ for ‘void obliczenia::sortowanie(int**, int, Komparator<int>*)’ does not match any template declaration
void sortowanie<int*>(int* * tablica, int rozmiar, Komparator<int> *komparator) {

Solution

  • Perhaps this is a typo.

    In the generic template version, you have:

    template <typename typ>
    void sortowanie(typ *tablica, int rozmiar, Komparator<typ> *komparator) {
    

    In the specialization, you have:

    template<>
    void sortowanie<int*>(int* * tablica, int rozmiar, Komparator<int> *komparator) {
                                                       ^^^^^^^^^^^^^^^^^^^^^^^^^^^
    

    I suspect you mean that to be: Komparator<int*> *komparator.

    Without that, the function can be an overload but it can't be a template specialization. In that case, you need to remove the template <> before the function declaration.