tags:

views:

1175

answers:

3

C++ seems to be rather grouchy when declaring templates across multiple files. More specifically, when working with templated classes, the linker expect all method definitions for the class in a single compiler object file. When you take into account headers, other declarations, inheritance, etc., things get really messy.

Are there any general advice or workarounds for organizing or redistributing templated member definitions across multiple files?

+2  A: 

Across how many files? If you just want to separate class definitions from implementation then try this article in the C++ faqs. That's about the only way I know of that works at the moment, but some IDEs (Eclipse CDT for example) won't link this method properly and you may get a lot of errors. However writing your own makefiles or using Visual C++ this has always worked for me :-)

Eric Scrivner
+9  A: 

Are there any general advice or workarounds for organizing or redistributing templated member definitions across multiple files?

Yes; don't.

The C++ spec permits a compiler to be able to "see" the entire template (declaration and definition) at the point of instantiation, and (due to the complexities of any implementation) most compilers retain this requirement. The upshot is that #inclusion of any template header must also #include any and all source required to instantiate the template.

The easiest way to deal with this is to dump everything into the header, inline where posible, out-of-line where necessary.

If you really regard this as an unacceptable affront, a common option is to split the template into the usual header/implementation pair, and then #include the implementation file at the end of the header.

C++'s "export" feature may or may not provide another workaround. The feature is poorly supported and poorly defined; although it in principle should permit some kind of separate compilation of templates, it doesn't necessarily obviate the demand that the compiler be able to see the entire template body.

DrPizza
A: 
jwfearn