| re: Template Instantiation
Russ Ford wrote:[color=blue]
> 34.13-14 of the FAQ shows that to instantiate a template, you can make
> another source file that includes the .cc file where the definition of the
> functions is contained:
> ---------------------------------
> foo.h:
> template <class T> void somefn();
>
> foo.cc
> template <class T> void somefn() {}
>
> foo-impl.cc
> #include "foo.h"
> #include "foo.cc"
> template void somefn<int> ();
> ---------------------------------
> My question: is it ok to just include the explicit instantiation at the end
> of foo.cc (as a macro)?[/color]
Sure it is. That's what you're essentially doing in foo-impl.cc, since
(as I understand it) in your example 'foo.cc' is not supposed to be
compiled separately and 'foo-impl.cc' is compiled instead.
[color=blue]
> It compiles OK, but I just want to make sure that
> I'm not creating problems long term. My idea is this:
> -----------------------------------
> foo.h (same)
>
> foo.cc:
> template <class T> void somefn() {}
>
> #define TEMPL_IMPL(T) template void somefn<T> ();
>
> TEMPL_IMPL(int);[/color]
Why do you think you need this macro at all? Besides, the macro when used
does not contain any reference to 'somefn'. It's unusual to have only one
function per module, so you will have a bunch of those macros sitting at
the bottom of the file, seems unnecessary. Are you concerned with saving
time typing or with making a mistake while typing? If the latter, then
the compiler will catch it, no? If the former, then you're still typing
the name of the macro twice, then '#define', and so on...
[color=blue]
> ------------------------------------
> Then I should only need to include foo.h in any file that wants to use an
> instance of somefn<int>, right?[/color]
Absolutely.
The disadvantage of this approach is that if I want somefn<char>, I won't
be able to have it because the implementation of the function is not
available to the compiler, only the declaration. Of course, if the users
of 'somefn' template are never going to use it with any other type but
'int', then everything is fine.
Victor |