1

I am using a template class to set the data type for a swap function. In the code if i initialize the function name as lower case letter it throws an error call of overloaded 'swap(double&, double&) is ambiguous but when i initialize the function name as upper case it works fine. Will appreciate if someone could explain me why this is happening. Here is my code

#include<iostream>

using namespace std;
template <class T>
void swap(T &a,T &b)
{
    T temp;

    temp = a;
    a = b;
    b = temp;
}

int main()
{
    double value1 = 2.44;
    double value2 = 6.66;

    cout<<"\tBefore swap \n";
    cout<<"Value 1 = "<< value1 <<"\tValue 2 = " << value2 <<"\n";

    swap(value1,value2);

    cout<<"\tafter swap \n";
    cout<<"Value 1 = "<< value1 <<"\tValue 2 = "<<value2;
}
Edward
  • 6,964
  • 2
  • 29
  • 55
Programmer
  • 39
  • 2
  • 10
  • `std::swap` is written in a way that it can be customized for your own types, but the process is quite obscure. Look at the first **two** answers in http://stackoverflow.com/questions/11562/how-to-overload-stdswap After you did that, just use `std::swap`. – pmr Apr 07 '14 at 13:33

4 Answers4

2

Instead of

swap(value1,value2);

use

::swap(value1,value2);

This would solve the namespace and ambiguity issue.

Dr. Debasish Jana
  • 6,980
  • 4
  • 30
  • 69
1

because there is already a standard library function std::swap http://www.cplusplus.com/reference/algorithm/swap/ so possibly your compiler does not like it? You pull that in via using namespace std;

Ferenc Deak
  • 34,348
  • 17
  • 99
  • 167
1

Change the name of your swap function because std::swap already exists.

Or you could put it in a separate namespace and use the scope resolution operator, "::", to distinguish yours from the standard one.

This is what happens when you use namespace std;. You may want to be more specific and use:

using std::cout;
using std::endl;
using std::cin;
Thomas Matthews
  • 56,849
  • 17
  • 98
  • 154
0

Already standard library function is defined with templates 'swap' Instead of 'SWAP',It is actually under the std namespace, but because you have a using namespace std line, it exists without the std:: prefix.

As you can see, using the using namespace std isn't always a good option because of possible name collisions, as in this example. In general one should prefer not to use the using directive unless there's a real reason for this - namespaces exist for a reason - to prevent name collisions.

BAP
  • 27
  • 2
  • 11