1

I am specifically asking about file structure and where to put what. Consider the following (this is an example of my current structure):

foo.h consists of:

template <typaname T>
class Foo {
  void bar();
}

#include "foo-inl.h"

foo-inl.h consists of:

template<typaneme T>
void Foo::bar() {
}

Some baz.cpp has:

#include "foo.h"

Foo<X> foo;

and some other nom_test.cpp has:

#include "foo.h"

Foo<TestY> foo;

How do I restructure this to take advantage of the explicit instantiation in both the prod code (baz.cpp) and test code (nom_test.cpp). Mind, I wouldn't like to expose the test types to the prod build.

gruszczy
  • 40,948
  • 31
  • 128
  • 181

1 Answers1

0

foo.h:

template <typename T>
class Foo {
  void bar();
}
#include "foo-inl.h"

extern template class Foo<X>; // means "Foo<X> is instantiated elsewhere"

foo-impl.cpp:

#include "foo.h"

template class Foo<X>; // instantiates Foo<X> here

baz.cpp:

#include "foo.h"
// can simply use Foo<X>, the impl will be linked from foo-impl.o

Similarly for the test build, foo-impl-test.cpp would contain:

#include "foo.h"

template class Foo<TestY>;

Keep in mind though that the semantics of explicitly instantiated templates is different - they are no longer inline! For this reason the usefulness of explicitly instantiated templates is limited. C++20 modules solve this in an entirely different and much more flexible way, so it might be worth waiting for that instead.

rustyx
  • 80,671
  • 25
  • 200
  • 267