Link to home
Start Free TrialLog in
Avatar of nietod
nietod

asked on

Templates declarations in header files?

Is it legal to have only a template declaration in a header file if the template is defined somewhere in a regular file?  That is,

For example, can I just include the header file "SomeClass.h" into the "SomeProgram.cpp" as long as the file "SomeClass.cpp" is compiled and linked into the program (but not included into "SomeProgram.cpp").  

****************SomeClass.h**************
template <class T> class SomeClass
{
public:
   int x;
   SomeClass(int i);  // Declared, not defined.
};
****************SomeClass.cpp**************
// Define constructor.
template <class T> SomeClass::SomeClass(int i);
{
  x = i;
}
****************SomeProgram.cpp**************
#include "someclass.h"
  SomeClass SC(5);

A EE client was trying to do this in a program and I didn't think it was allowed,  I just want to make sure.  It caused linker errors, which seems to make sense as things compiled, but the necessary functions weren't there.
Avatar of galkin
galkin

Actually template class public functions must be declared inline.
Yes, this is allowed according to the new C++ standard. It is called "separate template compilation". However, only a few compiler support it, and the ones I use are not among them :-(

See http://www.ses.com/~clarke/cpptips/templ_sep_comp_spec for a short explanation.
Avatar of nietod

ASKER

Sorry Galkin, but it looks like you are out of date.

Yonat, If you answer the question I'll give you the points.
I am not sure but I think that you have to use the extern keyword on the function bodies when they are not inline.
Danny Pav
Avatar of nietod

ASKER

Yes, that is correct.  Check the web site that yonat posted for details.
ASKER CERTIFIED SOLUTION
Avatar of yonat
yonat

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Gosh .. this C++ language thingy sure does get changed more than a baby on laxatives !!

It certainly keeps us poor experts on our toes .. and keeps those not-so-poor people that write compilers in jobs for a long time.