S
Sunil Varma
Hi,
I'm trying to write template functions and use them.
Is it possible to declare a template function in a .h file and define
it in a .cpp file.
Ex:
//temp_func.h
template <class T>void swap(T &left,T &right);
//temp_func.cpp
template <class T>void swap(T &left,T &right)
{
T temp = left;
left = right;
right = temp;
}
//main.cpp
#include <iostream>
#include "temp_func.h"
using namespace std;
main()
{
int a = 10, b = 20;
cout<<"Before swapping: a = "<<a<<", b = "<<b<<endl;
swap(a,b);
cout<<"After swapping: a = "<<a<<", b = "<<b<<endl;
}
When I built the above code, I got the following error:
undefined reference to 'void swap<int>(int&,int&)'
I know that the instantiation of the swap() function is not available
in temp_func.o.
But, how can one make the above code build successfully.
The above code builds properly if I define the swap() function in
the .h file itself.
How do the STL algorithms work?
Are those functions defined in the headers itself.
Thanks in advance.
Regards
Sunil
I'm trying to write template functions and use them.
Is it possible to declare a template function in a .h file and define
it in a .cpp file.
Ex:
//temp_func.h
template <class T>void swap(T &left,T &right);
//temp_func.cpp
template <class T>void swap(T &left,T &right)
{
T temp = left;
left = right;
right = temp;
}
//main.cpp
#include <iostream>
#include "temp_func.h"
using namespace std;
main()
{
int a = 10, b = 20;
cout<<"Before swapping: a = "<<a<<", b = "<<b<<endl;
swap(a,b);
cout<<"After swapping: a = "<<a<<", b = "<<b<<endl;
}
When I built the above code, I got the following error:
undefined reference to 'void swap<int>(int&,int&)'
I know that the instantiation of the swap() function is not available
in temp_func.o.
But, how can one make the above code build successfully.
The above code builds properly if I define the swap() function in
the .h file itself.
How do the STL algorithms work?
Are those functions defined in the headers itself.
Thanks in advance.
Regards
Sunil