1

i create a template but get error.

the template and main (this code in one cpp file):

#include <iostream>

using namespace std;

template<class T> 
void swap(T& x, T& y);

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

int main(){
int n1 = 10, n2 = 5;

cout << "number before swap: num1= " << n1 << " num2= " << n2 << endl;
swap(n1, n2);//compilation error
cout << "number after swap: num1= " << n1 << " num2= " << n2 << endl;

system("pause");
return 0;
}

error:

Error   1   error C2668: 'std::swap' : ambiguous call to overloaded function    
c:\projects\template\main.cpp   42  1   Template
2   IntelliSense: more than one instance of overloaded function "swap" 
matches the argument list:
        function template "void swap(T &x, T &y)"
        function template "void std::swap(_Ty &, _Ty &)"
        argument types are: (int, int)  c:\Projects\Template\main.cpp   43  
2   Template

why i get error i don't understand because all look fine. thank's for the help.

thank's.

liran
  • 19
  • 2
  • it appears that `std::swap` is declared inside ``. Which is not a requirement but which is completely valid. – Jarod42 May 05 '17 at 18:07

2 Answers2

6

You are using using namespace std;. Because of this, the compiler has no way of knowing whether the line swap(n1, n2); means to use std::swap or your custom swap. You can resolve the ambiguity by explicitly specifying the namespace to use. You can use :: to specify the global namespace, which is where you defined your swap function. Try:

int main()
{
    int n1 = 10, n2 = 5;

    cout << "number before swap: num1= " << n1 << " num2= " << n2 << endl;
    ::swap(n1, n2);
    cout << "number after swap: num1= " << n1 << " num2= " << n2 << endl;

    return 0;
}

However, the real solution here is to remove using namespace std;. See here for an explanation of why this is a bad practice.

Community
  • 1
  • 1
François Andrieux
  • 28,148
  • 6
  • 56
  • 87
0

If you must have a using namespace std declaration and implement your own swap function, you can change your function name to start with an uppercase, Swap(). Since C++ is case-sensitive, that will avoid the clash, and therefore the ambiguity. It's better practice to use the Standard Library version, however.

Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574
gguev75
  • 1
  • 1