Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is a template class compiled more than once in different compilation units in C++?

Tags:

c++

templates

Let's say I have the following code:

// templateClass.h
#ifndef TEMPLATE_CLASS_H
#define TEMPLATE_CLASS_H

template <typename T>
class tClass
{
public:
  tClass();
};

#endif

// templateClassDef.inl
#ifndef TEMPLATE_CLASS_DEF_INL
#define TEMPLATE_CLASS_DEF_INL

template <typename T>
tClass<T>::tClass()
{
}

#endif

// normalClass.h
#include "templateClass.h"

class normal
{
public:
  normal();
};

// normalClass.cpp
#include "normalClass.h"
#include "templateClassDef.inl"

normal::normal()
{
  tClass<int> a;
}

// main.cpp
#include "templateClass.h"
#include "templateClassDef.inl"

#include "normalClass.h"

int main()
{
  tClass<int> a;
  normal b;

  return 0;
}

Note that the inl file is NOT being included in the header as it normally is, but is instead included in the source files (I am aware that is not the standard way... this is just an example). Notice that normalcClass.cpp is instantiating tClass<int> and so is main.cpp.

I am curious as to whether the compiler has to construct the instantiation from the template class every time it encounters an explicit instantiation, considering it is the same type (i.e. tClass<int>) even though both instantiations occur in separate translation units (normalClass.cpp and main.cpp)? Also, will this increase in compile time (If the answer to the previous question is yes it will instantiate it again then this should also be yes)?

like image 510
Samaursa Avatar asked Dec 22 '22 02:12

Samaursa


1 Answers

Basically, templates are instantiated per compile unit, which increases compile time. There are some extensions and features in the new C++ standard to handle this issue, like explicit instantiation and externalization. See this doc for some explanations and optimization techniques:

http://gcc.gnu.org/onlinedocs/gcc/Template-Instantiation.html

like image 123
Sam Avatar answered Dec 24 '22 02:12

Sam