template function

X

xuatla

Hi,

I am trying to use template function and encounted some problems hope to
get your help. THANKS!

make output:

undefined reference to `int reallocateMemory<double>(double*&, int)'

( compile of auxifunc.o: OK; link: main.o auxifunc.o )
( makefile should be ok )

source code below:

==================
auxifunc.h

template < class T >
extern int reallocateMemory( T*& array, int newsize );

==================
auxifunc.cpp

template < class T >
int reallocateMemory( T*& array, int newsize )
{
delete[] array;

array = new T[newsize];

if ( !array ) return 0;
else return 1;
}

==================
main.cpp

#include "auxifunc.h"

int main()
{
double *a = new double[1];

reallocateMemory<double>( a, 10 );

return 1;
}

If I put the definition of reallocateMemory in .h file, then it's ok.

If I dont use template and put the prototype in .h and definition in
..cpp, also ok.

what's the problem in my case?

Do I need to seperate prototype and definition in two files (.h & .cpp)
instead of putting everything in .h?

When do I need to use "extern"?

Thanks a lot!

X
 
J

John Harrison

Hi,

I am trying to use template function and encounted some problems hope to
get your help. THANKS!

[snip]

If I put the definition of reallocateMemory in .h file, then it's ok.

If I dont use template and put the prototype in .h and definition in
.cpp, also ok.

what's the problem in my case?

Do I need to seperate prototype and definition in two files (.h & .cpp)
instead of putting everything in .h?

When do I need to use "extern"?

Thanks a lot!

No you need to put everything into the header file. All template code
should go into header files. The FAQ explains why

http://www.parashift.com/c++-faq-lite/containers-and-templates.html#faq-34.12

john
 
X

xuatla

IC. Thanks.

X

John said:
Hi,

I am trying to use template function and encounted some problems hope
to get your help. THANKS!

[snip]

If I put the definition of reallocateMemory in .h file, then it's ok.

If I dont use template and put the prototype in .h and definition in
.cpp, also ok.

what's the problem in my case?

Do I need to seperate prototype and definition in two files (.h &
.cpp) instead of putting everything in .h?

When do I need to use "extern"?

Thanks a lot!

No you need to put everything into the header file. All template code
should go into header files. The FAQ explains why

http://www.parashift.com/c++-faq-lite/containers-and-templates.html#faq-34.12


john
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,172
Messages
2,570,934
Members
47,474
Latest member
AntoniaDea

Latest Threads

Top