overloaded function is ambigious

I'm trying to code a template that will sort elements (whether int or double, etc). The sort somewhere calls a swap function to change the order so the elements appear in ascending order. In my main(), I would do bubbleSort(a, n) where 'a' is a pointer pointing to an array of integers (or doubles, etc) and 'n' is the size of the array. But when I compile, I get an error such as : call of overloaded 'swap(int&, int&)' is ambiguous....candidates are: void swap(T&, T&) [with T = int]


I then found out my swap function had to be coded as swap(T *a, T *b) and then everything worked fine. Why did I have to do this?

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
template <typename T>
void bubbleSort(T arr[], int n);

template <typename T>
void swap (T &a, T &b);

template <typename T>
void bubbleSort(T arr[], int n) {
        bool isSorted = false;
        for (int last = n-1; last > 0 && !isSorted; last--) {
                isSorted = true;
                for (int i = 0; i < last; i++)
                        if (arr[i] > arr[i+1]) {
                                swap(arr[i], arr[i+1]);
                                isSorted = false;
                        }   
                if (last % 1000 == 0) cerr << ".";
        }   
}

template <typename T>
void swap(T &a, T &b) {
        T *temp = a;
        a = b;
        b = temp;
}
I think the error is because you have using namespace std; somewhere so it doesn't know if it should call your swap function or std::swap.
Ah that makes sense. Thanks a lot
Also, why is your temp a pointer to T in the swap function? That feels like it should be a compiler error.
Topic archived. No new replies allowed.