template-fn implemented in different object does not link

R

reppisch

Hi Ng,

i tried to instantiate a template class in a different compilation unit
than it is implemented. It seems while linking it together the linker
does not call the compiler to generate the missing functions.

Doing it all in one object seems no problem.


How to reproduce:

--------------
scratchpad.hpp
--------------
template < typename T >
class TemplatedBase
{
public:
T member;
int foo(const T arg);
};

--------------
scratchmod.cpp
--------------
#include "scratchpad.hpp"

template < typename T >
int TemplatedBase<T>::foo (const T arg)
{
return 1;
}

--------------
scratchpad.cpp
--------------
#include "scratchpad.hpp"

int main()
{
char c = 42;
TemplatedBase<char> p;
p.foo(c);
}

--------------

g++ scratchpad.cpp scratchmod.cpp

/cygdrive/c/Temp/ccQbDL3c.o(.text+0x31):scratchpad.cpp: undefined
reference to `TemplatedBase<char>::foo(char)'

Is it a bug or a feature? And how to do it right?



Regards,

Michael
 
S

Sumit Rajan

reppisch said:
Hi Ng,

i tried to instantiate a template class in a different compilation unit
than it is implemented. It seems while linking it together the linker
does not call the compiler to generate the missing functions.

Doing it all in one object seems no problem.


How to reproduce:

--------------
scratchpad.hpp
--------------
template < typename T >
class TemplatedBase
{
public:
T member;
int foo(const T arg);
};

--------------
scratchmod.cpp
--------------
#include "scratchpad.hpp"

template < typename T >
int TemplatedBase<T>::foo (const T arg)
{
return 1;
}

--------------
scratchpad.cpp
--------------
#include "scratchpad.hpp"

int main()
{
char c = 42;
TemplatedBase<char> p;
p.foo(c);
}

--------------

g++ scratchpad.cpp scratchmod.cpp

/cygdrive/c/Temp/ccQbDL3c.o(.text+0x31):scratchpad.cpp: undefined
reference to `TemplatedBase<char>::foo(char)'

Is it a bug or a feature? And how to do it right?


See:
http://www.parashift.com/c++-faq-lite/templates.html#faq-35.12

Regards,
Sumit.
 

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
473,769
Messages
2,569,581
Members
45,056
Latest member
GlycogenSupporthealth

Latest Threads

Top