0

I'm trying to make a template function specialization for a bubble sort of character array's. For some reason though, when I'm about to define the function, I get an error underline over the function name and I have no idea why.

template<typename T>
T sort(T* a, T n) {
    int i, j;
    int temp;

    for (i = n - 1; i > 0; i--) {
        for (j = 0; j < i; j++) {
            if (a[j] > a[j + 1]) {
                temp = a[j];
                a[j] = a[j + 1];
                a[j + 1] = temp;
            }
        }
    }
}

template<>
const char* sort<const char*>(const char* a, const char* n) {

}
Constructor
  • 7,273
  • 2
  • 24
  • 66
onemic
  • 59
  • 1
  • 3
  • 10
  • The specialization does not match the template: there is no way to replace `T` with something, so that it gives the specialization. It looks as if `n` should not be of type `T`, but rather one of `int` (practical), `ptrdiff_t` (for pedantic formalists) or `size_t` (for the uninformed). I would go with the `int`, *if* I were to do this thing. – Cheers and hth. - Alf Apr 03 '14 at 02:18
  • By the way, it's generally a good idea (saves work) to declare each loop control variables in the loop head, e.g. `for( int i = n - 1; ...`. That's what the syntax is there for. This practice restrict the scope of the loop variable to the region of source code where it has a well-defined value, and thus prevents some possible bug scenarios. – Cheers and hth. - Alf Apr 03 '14 at 02:24
  • 1
    It's not recommended to specialize function templates. http://www.gotw.ca/publications/mill17.htm Provide a non-template _overload_ of `sort` for the `const char*` case instead. – Oktalist Apr 18 '14 at 13:01

1 Answers1

1

The problem:

When you replace T with const char *, the function signature looks like this:

const char* sort<const char*>(const char** a, const char* n)
                             //        ^^^ T* a -> const char ** a

Recommended:

Why is your signature template<typename T> T sort(T* a, T n) anyways? You aren't returning anything, and you are treating n as a size_t. I recommend changing your signature to this:

template<typename T> void sort(T* a, size_t n);

And your specialization to:

template<> void sort<char>(char* a, size_t n); 
yizzlez
  • 8,757
  • 4
  • 29
  • 44