Re: Using templates
On Jan 15, 12:43 pm, Sunil Varma <sunil....@gmail.com> wrote:
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.
Yes, but...
Ex:
//temp_func.h
template <class T>void swap(T &left,T &right);
You need to declare it extern here. Which is a problem, since a
lot of compilers aren't very up-to-date, and don't support
extern.
//temp_func.cpp
template <class T>void swap(T &left,T &right)
{
T temp = left;
left = right;
right = temp;
}
This is, obviously, the only reasonable organization. Given
that compilers don't support extern, howver, what you have to do
is add an ``#include "temp_func.cpp"'' to the end of your .h
file (and of course, ensure that the .cpp is exported along with
the .h file, when you provide a library).
A common convention is to use still a different naming
convention for these files. G++, for example, terminates them
with .tcc (as opposed to .cc and .hh). Typically, they are
designed to work only when included at the end of the .hh, and
shouldn't be included anywhere else.
Another possibility would be to use export when available, using
conditional compilation. Basically, your header looks something
like:
#ifndef TEMP_FUNC_CPP_andSomeRandomJunk
export template< typename T > void swap( T& left, T& right ) ;
#ifdef export
#include "temp_func.cpp"
#endif
#endif
If the compiler doesn't support export, you invoke it with
something like -Dexport= or /Dexport=, whatever is necessary to
define "export" as an empty string.
[...]
How do the STL algorithms work?
Are those functions defined in the headers itself.
It depends on the implementation---g++ does as I described, it
puts the implementations in a .tcc file, which is included from
the .hh.
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34