Problem with template
Feb 21, 2013 at 1:34pm UTC
The program is primitive, yet I still cann't find out mistake. Here the program is:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
#include <iostream>
using namespace std;
template <class X> void swap(X &a, X &b)
{
X temp;
temp = a;
a = b;
b = temp;
}
int main()
{
int i=10, j = 20;
float x=10.1, у= 23.3;
char a='x' , b='z' ;
cout << "Original i, j: " << i << ' ' << j << endl;
cout << "Original x, y: " << x << ' ' << у << endl;
cout << "Original a, b: " << a << ' ' << b << endl;
swap(i, j);
swap(x, у);
swap(a, b);
cout << "Swapped i, j : " << i << ' ' << j << endl;
cout << "Swapped x, y: " << x << ' ' << у << endl;
cout << "Swapped a, b: " << a << ' ' << b << endl;
return 0;
}
Last edited on Feb 21, 2013 at 1:52pm UTC
Feb 21, 2013 at 1:44pm UTC
What's wrong with it? The compiler must have said something.
We wouldn't expect to find these two together
1 2
#include <iostream.h>
using namespace std;
Did you mean this?
1 2
#include <iostream>
using namespace std;
Feb 21, 2013 at 1:52pm UTC
I am sorry about <iostream.h>. I did it like.
1 2
#include <iostream>
using namespace std;
The compiler sad:
22: error: call of overloaded 'swap(int&, int&)' is abiguous
23: error: call of overloaded 'swap(float&, float&)' is abiguous
24: error: call of overloaded 'swap(char&, char&)' is abiguous
Feb 21, 2013 at 2:05pm UTC
Somehow `algorithm' gets included.
Use namespaces to resolve the ambiguity.
Feb 21, 2013 at 2:07pm UTC
Can you explain deeper? I'm sorry, but I didn't understand you.
Previously thanks!
Feb 21, 2013 at 2:10pm UTC
ne555, thanks man I understood and did it through namespace. It really halped.
Feb 21, 2013 at 2:10pm UTC
Remove using namespace std;
And add std:: to cout etc. Works fine.
Feb 21, 2013 at 2:31pm UTC
No problem wasn't in cout.
I did like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
#include <iostream>
using namespace std;
namespace Swap
{
template <class X> void swap(X &a, X &b)
{
X temp;
temp = a;
a = b;
b = temp;
}
}
int main()
{
int i=10, j = 20;
float x=10.1, у= 23.3;
char a='x' , b='z' ;
cout << "Original i, j: " << i << ' ' << j << endl;
cout << "Original x, y: " << x << ' ' << у << endl;
cout << "Original a, b: " << a << ' ' << b << endl;
Swap::swap(i, j);
Swap::swap(x, у);
Swap::swap(a, b);
cout << "Swapped i, j : " << i << ' ' << j << endl;
cout << "Swapped x, y: " << x << ' ' << у << endl;
cout << "Swapped a, b: " << a << ' ' << b << endl;
return 0;
}
Last edited on Feb 21, 2013 at 2:32pm UTC
Topic archived. No new replies allowed.