Trevor Hickey
Trevor Hickey

Reputation: 37894

(C++) where do I put all my templates?

I have different classes all arranged in a hierarchy. To reduce the amount of code, I started creating template functions. The base class will use the template functions and some of the derived classes will also use the same functions. Where am I suppose to put all of these templates so I don't get undefined reference issues like I have been? Should I put all the definitions in a header file and then just include that header files in the .cpp part of the class that call the functions. will that work? As of right now, all of my classes(class.cpp, class.h) compile fine, but everything blows up during the linking. I tried to put all the templates in a namespace and then include that namespace in the implementation of all my classes but that doesn't seem to work. My question is, how would you go about making a separate entity that just holds templated functions that any class can use on it's data members?

Upvotes: 1

Views: 131

Answers (2)

Salvatore Previti
Salvatore Previti

Reputation: 9070

I see a lot of people confused by this thing... templates are not types. They become types when instantiated. For this reason members of templates must stay in the same data unit you are going to use them.

If you template is generic and you want to use it in all your code, just put everything in header files.

Now, if you don't like (and i would understand that) that you show declarations and definitions and implementation all in the same file, you can split templates in two different files.

For example, "list.h" with your declaration and "list.inc" with your implementation.

To make it work, you have to include both.

Upvotes: 1

Ken Bloom
Ken Bloom

Reputation: 58790

The definitions of template functions and template classes belong in header files, not .cpp files.

This is because the compiler essentially has to generate a brand new function for each set of template parameters that's used in the file that #includes the header. If the template function were defined in a .cpp file, then all of the appropriate versions of these functions would have to be generated without knowing what the calling code looks like, and that's basically impossible. (You do get duplicate definitions of template functions this way, but the linker removes those and makes sure there's only one copy if each template instantiation in the final binary.)

Upvotes: 2

Related Questions