|
|
|
|
Header files
Even if you create non-inline function
definitions, you’ll usually want to put all declarations and
definitions for a template into a header file. This may seem to violate the
normal header file rule of “Don’t put in anything that allocates
storage,” (which prevents multiple definition errors at link time), but
template definitions are special. Anything preceded by
template<...> means the compiler won’t allocate storage for
it at that point, but will instead wait until it’s told to (by a template
instantiation), and that somewhere in the compiler and linker there’s a
mechanism for removing multiple definitions of an
identical template. So you’ll almost always put the entire template
declaration and definition in the header file, for ease of
use.
There are times when you may need to
place the template definitions in a separate cpp file to satisfy special
needs (for example, forcing template instantiations to exist in only a single
Windows dll file). Most compilers have some mechanism to allow this;
you’ll have to investigate your particular compiler’s documentation
to use it.
Some people feel that putting all of the
source code for your implementation in a header file makes it possible for
people to steal and modify your code if they buy a library from you. This might
be an issue, but it probably depends on the way you look at the problem: Are
they buying a product or a service? If it’s a product, then you have to do
everything you can to protect it, and probably you don’t want to give
source code, just compiled code. But many people see software as a service, and
even more than that, a subscription service. The customer wants your expertise,
they want you to continue maintaining this piece of reusable code so that they
don’t have to – so they can focus on getting their job done.
I personally think most customers will treat you as a valuable resource and will
not want to jeopardize their relationship with you. As for the few who want to
steal rather than buy or do original work, they probably can’t keep up
with you
anyway.
|
|
|