Rob Rob - 11 months ago 39
C++ Question

What is the correct way to implement a C++ template in a Visual Studio 2015 solution?

I have an assignment in my computer science class where we need to create a templatized version of a C++ class. Our instructor has given us little to no instruction regarding the matter so I've been fumbling through the assignment.

I seem to have made the code from our book work, but I'm not sure the approach I used is appropriate.

Essentially, the example they provide in the book is a "bag" class which is a simple container used to store any manner of standard data types (int, char, string, etc.). The templatized version of this class is declared in a header file called bag5.h and the implementation is given in a .template file called bag5.template. The header then retrieves the code from the .template file using this line, which is near the very end of the header:

#include "bag5.template"

At first I wasn't sure how to implement a file of type .template in a C++ solution using Visual Studio 2015. I searched for an answer but unfortunately, searching for the terms "visual studio" and "template" provide nearly limitless results on how to create templates for visual studio projects, but very little I could find on properly implementing generic C++ templates in Visual Studio.

Through trial and error, I finally got the source code to work by adding the .template files to the solution as a file of type "text" rather than as a C++ source file. My question is simple: Is this the correct way to implement the definition for a declared template using Visual Studio 2015?

Also, is there any way to get Visual Studio 2015 to recognize my .template files as C++ code and format them accordingly? When I add the .template implementation files as type "text" within the solution, the IDE does not color code the text inside the files, it leaves it completely black on white text.

Answer Source

The usual way to do this is to put the code for the template directly in the header.

If you really want to keep the code separate from the declarations, you can choose two different extensions that VC++ recognizes as headers, and have the one include the other. For example, have bag5.h, which includes bag5.hh.

As long as both extensions are recognized by VC++ as headers, life is pretty good--you don't have to do much to tell it how to work with them, and it'll automatically apply color coding to both.