-
Template Program..
This is a program to swap two numbers...implemented using template...
Code:
#include <iostream>
using namespace std;
template <class T>
void swap(T &x, T &y)
{
T temp = x;
x = y;
y = temp;
}
void fun(int m,int n,float a,float b)
{
cout << "m and n before swap" << m << " " << n << " " << endl;
swap(m,n);
cout << "m and n after swap" << m << " " << n << " " << endl;
cout << "a and b before swap" << a << " " << b << " " << endl;
swap(a,b);
cout << "a and b ater swap" << a << " " << b << " " << endl;
}
int main()
{
fun(100,200,11.22,33.44);
return 0;
}
i am not able to understand the line......
Code:
void swap(T &x,T &y)
Can somebody please explain what this statement is doing...??
Thanks in advance..
-
Do you understand references in C++? (It seems unlikely that you would learn to write function templates before learning about C++ references.)
By the way, be careful about the using namespace std; combined with a function template named swap because there is already such a function template in the std namespace.
-
while calling the function we just said..
.
.
which means we are actually passing the values of m and n
....
then while recieving it why did we use...
Code:
void swap(T &a,T &b);
-
Because you want to pass by reference so that the swap will be reflected in the caller. If you don't understand this, then you need to refer to introductory material on C++ concerning references.
-
yeah..i know when we use pass by reference then in while calling we use...
and while recieving it we use..
Code:
void swap(int *p,int *q)
There is no use of the pointer here... so i am getting confused...
-
Dude, laserlight is telling you that C++ has two forms of reference semantics: pointers (which you apparently know) and references (which you clearly don't).
If you don't understand references, that's fine; it is not big deal, but for Yog Sothoth, please stop saying you know and just go and read about C++ references.
Soma
-
The reference syntax was somewhat confusing to me when I started learning C++.
Read this out. [8] References, C++ FAQ
-
What you have shown is call by reference simulated by the passing of pointers. This is related to call by reference through the use of reference parameters, but is not the same thing.
You need to read whatever you read to learn C++, or perhaps read a tutorial like the cprogramming.com tutorial on references.
-
ok...ok...references are really a little confusing for me...
-
Be careful in what you call pass by reference.
What you showed is pass by address or by pointer.
It could be called pass by reference (and indeed, it is often called thus in C), but in C++ there is an actual feature in the language that is called a reference and by using them we are said to pass by reference. Therefore, you should not mix these two as it will cause confusion.
T* x, T* y
&m, &n
This is called pass by pointer or by address.
T& x, T& y
m, n
This is called pass by reference.