0

I am trying to use c++ template generics with a void function,

The code:

#include <iostream>

using namespace std;

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

int main() 
{
    cout << "Swapper!" << endl;
    int x, y;
    cin >> x >> y;
    swap(x, y);
    cout << x << y;
    cin.get();
    return 0;
}

But it gives an error:

call of overloaded swap() is ambiguous

How do I remove this error?

jonsno
  • 279
  • 4
  • 17

2 Answers2

3

The problem is using namespace std;. You should almost never use this line anywhere in your code. A good approach is to instead just quality all std names, i.e. write std::cout << "Swapper!" << std::endl; instead of cout << "Swapper!" << endl;.

In this particular case, your own swap function conflicts with std::swap, which you indirecty get via <iostream>. While std::swap is only guaranteed to exist in <algorithm> and <utility>, all C++ standard headers are allowed to pull in any other C++ standard headers.

So once you include any standard header, using namespace std; creates a potential conflict with all names in std.

Christian Hackl
  • 27,051
  • 3
  • 32
  • 62
2

You should remove using namespace std; because this namespace already contains a function called swap and the compiler doesn't know which one to choose. To be honest, you don't really need to write such a function yourself, it has already been done for you.

Another way is to rename your function to something other than swap.

ForceBru
  • 43,482
  • 10
  • 63
  • 98