Template Instantiation

R

Russ Ford

Hi all,

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)? 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);
 
V

Victor Bazarov

Russ said:
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> ();

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.
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);

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...

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,756
Messages
2,569,535
Members
45,008
Latest member
obedient dusk

Latest Threads

Top