0

I am coding C++ in Visual Studio 2015. I have files called superpixel.h and superpixel.cpp. I wanted to use templates for some of the functions but I read that I can't define templates in cpp files. I don't want to define the templates in the header file because it will just make my code messy with definitions in header and cpp files.

Is there a work around to this ? Do I have to switch all my cpp files to hpp ?

halfer
  • 19,824
  • 17
  • 99
  • 186
Kong
  • 2,202
  • 8
  • 28
  • 56
  • Some create a .inl (inline) file that's included in the bottom of the .h file. This file will then contain all template methods. – Shaggi Nov 19 '16 at 04:12
  • I was also a bit annoyed about this when I first learned templates. It sounded kind of unbelievable, but I did some Google-ing and it seemed pretty standard to just do the implementation in the header so I accepted it. – RareTyler Nov 19 '16 at 04:14

1 Answers1

0

Anything using the template will need access to the template, which means it has to be included. Most of what I have seen is putting the entire definition into the header, although you could move it into some other file and include that. If you keep your header files to one per class, it hopefully won't be all that messy.

You don't have to switch all of your cpp files to hpp. Those are just extensions and they mostly don't matter. Although you may want to consider going header only if your code is mostly template as the template code will have to be in headers anyway and header only projects are typically a bit easier to include in other projects since you don't have to worry about linking.

Daniel Underwood
  • 2,191
  • 2
  • 22
  • 48
  • 1
    This is poor advice. The entire point of header and source is that when you include the header file it only includes the requested parts of the header which makes the include significantly smaller than having your entire code in the header. – matt2405 Nov 19 '16 at 18:13
  • Header only libraries are actually a quite common practice. See [Boost](http://www.boost.org/), which is quite possibly the most used C++ library. But that is largely up to the author. The traditional route and dynamic linking is also very useful at times. But either way, the template code _must_ be in the header files for it to work where it is included. Or at least the base templates if the template specializations are defined elsewhere. Then those specializations must also be included where necessary. – Daniel Underwood Nov 19 '16 at 18:25