praveen
praveen

Reputation: 53

Why is the template function ambiguous?

When I compile this code I get an error saying

call of overloaded swap(int&, int&) is ambiguous

but I've written only one swap function here.

Can you tell me why the function was ambiguous and what changes I need to do to run the program correctly?

using namespace std;

template <class T>
void swap(T& x, T& y)
{
    T temp;
    temp = x;
    x = y;
    y = temp;
}

int main()
{
    int a, b;

    cout << "Enter two elements: ";

    cin >> a;
    cin >> b;

    swap(a, b);
    cout << "a is "<<a << '\t'<<"b is " << b << std::endl;

    return 0;
}

Why was the swapping function overloaded even though it has only only swap function?

Upvotes: 0

Views: 153

Answers (2)

taocp
taocp

Reputation: 23634

You should use

 ::swap(a,b); //use one in global namespace, which is the one you defined

if you would like to call the one you defined. Since std has also defined a swap function template, the compiler will search for std namespace if you do not use ::.

More specifically, the parameter a and b are of type int, which is defined in std namespace, when compiler searches for swap, it will find both versions: the one in std namespace and the other you defined in global namespace. You need to tell compiler which one it should use explicitly, otherwise, it will lead to ambiguity.

Upvotes: 3

Muscles
Muscles

Reputation: 471

Because you have "using namespace std;", and presumably you are including "algorithm", you have visibility of std::swap. This gives you the ambiguity that the compiler is warning you about.

The solution is either not to add "using namespace std;", or to call your own function in the unnamed namespace explicitly, by calling it as "::swap(a, b)"

Upvotes: 2

Related Questions