Skip to content

Explicit Template Instantiation

Christian Glusa edited this page May 4, 2026 · 2 revisions

How Explicit Template Instantiation (ETI) works:

Great writeup: https://stackoverflow.com/questions/2351148/explicit-template-instantiation-when-is-it-used The post also has a script that can be used to identify good candidates for applying ETI.

The steps for implementing ETI are as follows. They can be done by hand, but that's pretty tedious.

Starting from name.hpp and name.cpp:

  • Split declarations and definitions into name_decl.hpp and name_def.hpp.
  • Have name.hpp that only includes name_decl.hpp.
  • Have name.cpp with template instantiations.

How ETI is done in Trilinos

Generate name.hpp files from name_decl.hpp and name_def.hpp

INCLUDE(TrilinosCreateClientTemplateHeaders)
TRILINOS_CREATE_CLIENT_TEMPLATE_HEADERS(${DIR})

This way, if explicit instantiation is turned off, it will generate includes for name_decl.hpp and name_def.hpp in name.hpp.

Generate name.cpp files

TRIBITS_ADD_EXPLICIT_INSTANTIATION_OPTION()

adds the CMake option and variable for package ETI support. The variable also needs to be exposed as a cmakedefine in a config.h file.

TRIBITS_ADD_ETI_SUPPORT()

adds the package to the TriBITS maintained list of packages that do ETI. If ETI is enabled, TriBITS calls cmake/ExplicitInstantiationSupport.cmake

See packages/ifpack2/cmake/ExplicitInstantiationSupport.cmake for an example.

This is used to generate a file Package_ETIHelperMacros.h with ETI macros.

For generating the cpp files that call the macros we can use the Tpetra CMake functions which use a file template for the cpp. See packages/ifpack2/src/CMakeLists.txt for an example.

These template files should:

  • Include config.h file to get access to the HAVE_PACKAGE_EXPLICIT_INSTANTIATION #define.
  • Have an #if that checks whether the cpp should be used, i.e. if we are instantiating the combination of template args. (I believe this is needed in case we reconfigure and old *.cpps are still around.)
  • Include the Package_ETIHelperMacros.h file to get the ETI macros.
  • Include name_decl.hpp and name_def.hpp
  • Call correct macro for instantiation.

The last step is to define a macro in name_def.hpp that will be called.

There are also macros defined in packages/teuchos/core/src/Teuchos_ExplicitInstantiationHelpers.hpp to instantiate scalar types only. Thyra uses them.

MueLu uses a slightly different approach that directly generates the instantiation macro as part of the cpp. The downside to this is that it is more involved to add something that is not a class.

Clone this wiki locally