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;
}
Instead of
swap(value1,value2);
use
::swap(value1,value2);
This would solve the namespace and ambiguity issue.
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;
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;
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.