Code doesn't compile ? Function overloading


Line 23|error: call of overloaded 'swap(int&, int&)' is ambiguous

Why is it telling me this? I thought I was allowed ambiguity with function templates?

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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
#include <iostream>
template <class any>
void swap(any &a, any &b);

struct job
{
    char name[40];
    double salary;
    int floor;
};

template <> void swap<job>(job &j1, job &j2);
void show(job &j);

int main()
{
    using namespace std;
    cout.precision(2);
    cout.setf(ios::fixed, ios::floatfield);
    int i = 10, j = 20;
    cout << "i, j = " << i << ", " << j << ".\n";
    cout << "Using compiler generated int swapper:\n";
    swap(i, j);
    cout << "Now i, j = " << i << ", " << j << ".\n";

    job sue = {"Susan Yaffee", 73000.60, 7};
    job sidney = {"Sidney Taffee", 68550.23, 8};
    cout << "Before job swapping:\n";
    show(sue);
    show(sidney);
    cout << "After job swapping:\n";
    show(sue);
    show(sidney);
    return 0;
}

template <class any>
void swap(any &a, any &b)
    {
        any temp;
        temp = a;
        a = b;
        b = temp;
    }

template <> void swap<job>(job &j1, job &j2)
{
    double t1;
    int t2;
    t1 = j1.salary;
    j1.salary = j2.salary;
    k2.salary = t1;
    t2 = j1.floor;
    j1.floor = j2.floor;
    j2.floor = t2;
}

void show(job &j)
{
    using namespace std;
    cout << j.name << ": $" << j.salary << " on floor " << j.floor << endl;
}
closed account (zb0S216C)
The compiler doesn't know which of the two template swap( ) functions to call since there's not enough information to separate them. The amount of parameters are the same, the identifier is the same, so is the return type-specifier. Basically, both function interfaces are the exact same. Here's your problem:

1
2
3
4
5
6
// The compiler is getting confused with this:
template <class any>
void swap(any &a, any &b); // (sic)

// and this:
template <> void swap<job>(job &j1, job &j2) // (sic) 

You need to rename one of them or make the either function more identifiable, if you will.

Wazzak
Last edited on
My first thought was that it was mixing up his version of swap with std::swap and couldn't figure out which to use. I don't think the template specialization has anything to do with it.

Solutions:
1) don't do using namespace std;
or
2) name your swap function something else.
ah shoot alright, thank you.
Topic archived. No new replies allowed.