Why can templates only be implemented in the header file?











up vote
1455
down vote

favorite
638












Quote from The C++ standard library: a tutorial and handbook:




The only portable way of using templates at the moment is to implement them in header files by using inline functions.




Why is this?



(Clarification: header files are not the only portable solution. But they are the most convenient portable solution.)










share|improve this question




















  • 45




    The question is incorrect. There is another portable way. The template class can be explicitly instantiated - as has been pointed out by other answers.
    – Aaron McDaid
    Aug 27 '12 at 11:42






  • 10




    While it is true that placing all template function definitions into the header file is probably the most convenient way to use them, it is still not clear what's "inline" doing in that quote. There's no need to use inline functions for that. "Inline" has absolutely nothing to do with this.
    – AnT
    Sep 18 '14 at 4:11








  • 6




    Book is out of date.
    – gerardw
    Oct 11 '14 at 13:25















up vote
1455
down vote

favorite
638












Quote from The C++ standard library: a tutorial and handbook:




The only portable way of using templates at the moment is to implement them in header files by using inline functions.




Why is this?



(Clarification: header files are not the only portable solution. But they are the most convenient portable solution.)










share|improve this question




















  • 45




    The question is incorrect. There is another portable way. The template class can be explicitly instantiated - as has been pointed out by other answers.
    – Aaron McDaid
    Aug 27 '12 at 11:42






  • 10




    While it is true that placing all template function definitions into the header file is probably the most convenient way to use them, it is still not clear what's "inline" doing in that quote. There's no need to use inline functions for that. "Inline" has absolutely nothing to do with this.
    – AnT
    Sep 18 '14 at 4:11








  • 6




    Book is out of date.
    – gerardw
    Oct 11 '14 at 13:25













up vote
1455
down vote

favorite
638









up vote
1455
down vote

favorite
638






638





Quote from The C++ standard library: a tutorial and handbook:




The only portable way of using templates at the moment is to implement them in header files by using inline functions.




Why is this?



(Clarification: header files are not the only portable solution. But they are the most convenient portable solution.)










share|improve this question















Quote from The C++ standard library: a tutorial and handbook:




The only portable way of using templates at the moment is to implement them in header files by using inline functions.




Why is this?



(Clarification: header files are not the only portable solution. But they are the most convenient portable solution.)







c++ templates c++-faq






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Feb 24 '15 at 20:54









Aaron McDaid

18.9k54774




18.9k54774










asked Jan 30 '09 at 10:06









MainID

9,969184769




9,969184769








  • 45




    The question is incorrect. There is another portable way. The template class can be explicitly instantiated - as has been pointed out by other answers.
    – Aaron McDaid
    Aug 27 '12 at 11:42






  • 10




    While it is true that placing all template function definitions into the header file is probably the most convenient way to use them, it is still not clear what's "inline" doing in that quote. There's no need to use inline functions for that. "Inline" has absolutely nothing to do with this.
    – AnT
    Sep 18 '14 at 4:11








  • 6




    Book is out of date.
    – gerardw
    Oct 11 '14 at 13:25














  • 45




    The question is incorrect. There is another portable way. The template class can be explicitly instantiated - as has been pointed out by other answers.
    – Aaron McDaid
    Aug 27 '12 at 11:42






  • 10




    While it is true that placing all template function definitions into the header file is probably the most convenient way to use them, it is still not clear what's "inline" doing in that quote. There's no need to use inline functions for that. "Inline" has absolutely nothing to do with this.
    – AnT
    Sep 18 '14 at 4:11








  • 6




    Book is out of date.
    – gerardw
    Oct 11 '14 at 13:25








45




45




The question is incorrect. There is another portable way. The template class can be explicitly instantiated - as has been pointed out by other answers.
– Aaron McDaid
Aug 27 '12 at 11:42




The question is incorrect. There is another portable way. The template class can be explicitly instantiated - as has been pointed out by other answers.
– Aaron McDaid
Aug 27 '12 at 11:42




10




10




While it is true that placing all template function definitions into the header file is probably the most convenient way to use them, it is still not clear what's "inline" doing in that quote. There's no need to use inline functions for that. "Inline" has absolutely nothing to do with this.
– AnT
Sep 18 '14 at 4:11






While it is true that placing all template function definitions into the header file is probably the most convenient way to use them, it is still not clear what's "inline" doing in that quote. There's no need to use inline functions for that. "Inline" has absolutely nothing to do with this.
– AnT
Sep 18 '14 at 4:11






6




6




Book is out of date.
– gerardw
Oct 11 '14 at 13:25




Book is out of date.
– gerardw
Oct 11 '14 at 13:25












14 Answers
14






active

oldest

votes

















up vote
1266
down vote



accepted










It is not necessary to put the implementation in the header file, see the alternative solution at the end of this answer.



Anyway, the reason your code is failing is that, when instantiating a template, the compiler creates a new class with the given template argument. For example:



template<typename T>
struct Foo
{
T bar;
void doSomething(T param) {/* do stuff using T */}
};

// somewhere in a .cpp
Foo<int> f;


When reading this line, the compiler will create a new class (let's call it FooInt), which is equivalent to the following:



struct FooInt
{
int bar;
void doSomething(int param) {/* do stuff using int */}
}


Consequently, the compiler needs to have access to the implementation of the methods, to instantiate them with the template argument (in this case int). If these implementations were not in the header, they wouldn't be accessible, and therefore the compiler wouldn't be able to instantiate the template.



A common solution to this is to write the template declaration in a header file, then implement the class in an implementation file (for example .tpp), and include this implementation file at the end of the header.



// Foo.h
template <typename T>
struct Foo
{
void doSomething(T param);
};

#include "Foo.tpp"

// Foo.tpp
template <typename T>
void Foo<T>::doSomething(T param)
{
//implementation
}


This way, implementation is still separated from declaration, but is accessible to the compiler.



Another solution is to keep the implementation separated, and explicitly instantiate all the template instances you'll need:



// Foo.h

// no implementation
template <typename T> struct Foo { ... };

//----------------------------------------
// Foo.cpp

// implementation of Foo's methods

// explicit instantiations
template class Foo<int>;
template class Foo<float>;
// You will only be able to use Foo with int or float


If my explanation isn't clear enough, you can have a look at the C++ Super-FAQ on this subject.






share|improve this answer



















  • 68




    Actually the explicit instantiation needs to be in a .cpp file which has access to the definitions for all of Foo's member functions, rather than in the header.
    – Mankarse
    May 28 '11 at 10:21








  • 9




    "the compiler needs to have access to the implementation of the methods, to instantiate them with the template argument (in this case int). If these implementations were not in the header, they wouldn't be accessible" But why is an implementation in the .cpp file not accessible to the compiler? A compiler can also access .cpp information, how else would it turn them into .obj files? EDIT: answer to this question is in the link provided in this answer...
    – xcrypt
    Jan 14 '12 at 23:56








  • 25




    I don't think this explains the question that clearly, the key thing is obviously related with the compilation UNIT which is not mentioned in this post
    – zinking
    Aug 23 '12 at 9:47






  • 4




    @Gabson: structs and classes are equivalent with the exception that the default access modifier for classes is "private", while it is public for structs. There are some other tiny differences that you can learn by looking at this question.
    – Luc Touraille
    Feb 21 '14 at 14:12






  • 1




    Use explicit instantiation otherwise you will get very slow builds soon..
    – Nils
    Jul 14 '14 at 13:43


















up vote
209
down vote













Plenty correct answers here, but I wanted to add this (for completeness):



If you, at the bottom of the implementation cpp file, do explicit instantiation of all the types the template will be used with, the linker will be able to find them as usual.



Edit: Adding example of explicit template instantiation. Used after the template has been defined, and all member functions has been defined.



template class vector<int>;


This will instantiate (and thus make available to the linker) the class and all its member functions (only). Similar syntax works for template functions, so if you have non-member operator overloads you may need to do the same for those.



The above example is fairly useless since vector is fully defined in headers, except when a common include file (precompiled header?) uses extern template class vector<int> so as to keep it from instantiating it in all the other (1000?) files that use vector.






share|improve this answer



















  • 32




    Ugh. Good answer, but no real clean solution. Listing out all possible types for a template does not seem to go with what a template is supposed to be.
    – Jiminion
    Jul 17 '14 at 17:49






  • 5




    This can be good in many cases but generally breaks the purpose of template which is meant to allow you to use the class with any type without manually listing them.
    – Tomáš Zato
    Dec 9 '14 at 3:27








  • 4




    vector is not a good example because a container is inherently targeting "all" types. But it does happen very frequently that you create templates that are only meant for a specific set of types, for instance numeric types: int8_t, int16_t, int32_t, uint8_t, uint16_t, etc. In this case, it still makes sense to use a template, but explicitly instantiating them for the whole set of types is also possible and, in my opinion, recommended.
    – UncleZeiv
    Jun 3 '15 at 15:41










  • Used after the template has been defined, "and all member functions has been defined". Thanks !
    – Vitt Volt
    Feb 16 '17 at 6:04












  • I'd like to know, is it possible to do the explicit instantiations from somewhere other than the class' header or source file? For instance, do them in main.cpp?
    – gromit190
    Mar 9 '17 at 8:01


















up vote
185
down vote













It's because of the requirement for separate compilation and because templates are instantiation-style polymorphism.



Lets get a little closer to concrete for an explanation. Say I've got the following files:




  • foo.h

    • declares the interface of class MyClass<T>



  • foo.cpp

    • defines the implementation of class MyClass<T>



  • bar.cpp

    • uses MyClass<int>




Separate compilation means I should be able to compile foo.cpp independently from bar.cpp. The compiler does all the hard work of analysis, optimization, and code generation on each compilation unit completely independently; we don't need to do whole-program analysis. It's only the linker that needs to handle the entire program at once, and the linker's job is substantially easier.



bar.cpp doesn't even need to exist when I compile foo.cpp, but I should still be able to link the foo.o I already had together with the bar.o I've only just produced, without needing to recompile foo.cpp. foo.cpp could even be compiled into a dynamic library, distributed somewhere else without foo.cpp, and linked with code they write years after I wrote foo.cpp.



"Instantiation-style polymorphism" means that the template MyClass<T> isn't really a generic class that can be compiled to code that can work for any value of T. That would add overhead such as boxing, needing to pass function pointers to allocators and constructors, etc. The intention of C++ templates is to avoid having to write nearly identical class MyClass_int, class MyClass_float, etc, but to still be able to end up with compiled code that is mostly as if we had written each version separately. So a template is literally a template; a class template is not a class, it's a recipe for creating a new class for each T we encounter. A template cannot be compiled into code, only the result of instantiating the template can be compiled.



So when foo.cpp is compiled, the compiler can't see bar.cpp to know that MyClass<int> is needed. It can see the template MyClass<T>, but it can't emit code for that (it's a template, not a class). And when bar.cpp is compiled, the compiler can see that it needs to create a MyClass<int>, but it can't see the template MyClass<T> (only its interface in foo.h) so it can't create it.



If foo.cpp itself uses MyClass<int>, then code for that will be generated while compiling foo.cpp, so when bar.o is linked to foo.o they can be hooked up and will work. We can use that fact to allow a finite set of template instantiations to be implemented in a .cpp file by writing a single template. But there's no way for bar.cpp to use the template as a template and instantiate it on whatever types it likes; it can only use pre-existing versions of the templated class that the author of foo.cpp thought to provide.



You might think that when compiling a template the compiler should "generate all versions", with the ones that are never used being filtered out during linking. Aside from the huge overhead and the extreme difficulties such an approach would face because "type modifier" features like pointers and arrays allow even just the built-in types to give rise to an infinite number of types, what happens when I now extend my program by adding:




  • baz.cpp

    • declares and implements class BazPrivate, and uses MyClass<BazPrivate>




There is no possible way that this could work unless we either




  1. Have to recompile foo.cpp every time we change any other file in the program, in case it added a new novel instantiation of MyClass<T>

  2. Require that baz.cpp contains (possibly via header includes) the full template of MyClass<T>, so that the compiler can generate MyClass<BazPrivate> during compilation of baz.cpp.


Nobody likes (1), because whole-program-analysis compilation systems take forever to compile , and because it makes it impossible to distribute compiled libraries without the source code. So we have (2) instead.






share|improve this answer



















  • 26




    emphasized quote a template is literally a template; a class template is not a class, it's a recipe for creating a new class for each T we encounter
    – v.oddou
    Apr 25 '16 at 9:57










  • I'd like to know, is it possible to do the explicit instantiations from somewhere other than the class' header or source file? For instance, do them in main.cpp?
    – gromit190
    Mar 9 '17 at 8:01






  • 1




    @Birger You should be able to do it from any file that has access to the full template implementation (either because it's in the same file or via header includes).
    – Ben
    Mar 9 '17 at 11:02










  • How's this an answer? It provides no solution but rhetoric only.
    – ajeh
    Apr 2 at 18:48






  • 4




    @ajeh It's not rhetoric. The question is "why do you have to implement templates in a header?", so I explained the technical choices the C++ language makes that lead to this requirement. Before I wrote my answer others already provided workarounds that are not full solutions, because there can't be a full solution. I felt those answers would be complemented by a fuller discussion of the "why" angle of the question.
    – Ben
    Apr 2 at 22:02


















up vote
67
down vote













Templates need to be instantiated by the compiler before actually compiling them into object code. This instantiation can only be achieved if the template arguments are known. Now imagine a scenario where a template function is declared in a.h, defined in a.cpp and used in b.cpp. When a.cpp is compiled, it is not necessarily known that the upcoming compilation b.cpp will require an instance of the template, let alone which specific instance would that be. For more header and source files, the situation can quickly get more complicated.



One can argue that compilers can be made smarter to "look ahead" for all uses of the template, but I'm sure that it wouldn't be difficult to create recursive or otherwise complicated scenarios. AFAIK, compilers don't do such look aheads. As Anton pointed out, some compilers support explicit export declarations of template instantiations, but not all compilers support it (yet?).






share|improve this answer



















  • 1




    "export" is standard, but it's just hard to implement so most of the compiler teams just haven't done yet.
    – vava
    Jan 30 '09 at 10:27






  • 5




    export doesn't eliminate the need for source disclosure, nor does it reduce compile dependencies, while it requires a massive effort from compiler builders. So Herb Sutter himself asked compiler builders to 'forget about' export. As the time investment needed would be better spend elsewhere...
    – Pieter
    Jan 30 '09 at 15:13






  • 2




    So I don't think export isn't implemented 'yet'. It'll probably never get done by anyone else than EDG after the others saw how long it took, and how little was gained
    – Pieter
    Jan 30 '09 at 15:14






  • 3




    If that interests you, the paper is called "Why we can't afford export", it's listed on his blog (gotw.ca/publications) but no pdf there (a quick google should turn it up though)
    – Pieter
    Jan 30 '09 at 15:22










  • Ok, thanks for good example and explanation. Here is my question though: why compiler cannot figure out where template is called, and compile those files first before compiling definition file? I can imagine it can be done in a simple case... Is the answer that interdependencies will mess up the order pretty fast?
    – Vlad
    Oct 11 '13 at 17:54


















up vote
50
down vote













Actually, prior to C++11 the standard defined the export keyword that would make it possible to declare templates in a header file and implement them elsewhere.



None of the popular compilers implemented this keyword. The only one I know about is the frontend written by the Edison Design Group, which is used by the Comeau C++ compiler. All others required you to write templates in header files, because the compiler needs the template definition for proper instantiation (as others pointed out already).



As a result, the ISO C++ standard committee decided to remove the export feature of templates with C++11.






share|improve this answer



















  • 38




    In a consequence export template was removed from C++11.
    – johannes
    Oct 23 '11 at 0:47






  • 5




    @johannes: I didn't catch that, thanks. Practically speaking, you couldn't use export anyway since that would tie you in with the Comeau compiler. It was a "dead feature"; just one I would have loved to see implemented ubiquitously.
    – DevSolar
    Oct 23 '11 at 6:06






  • 3




    ...and a couple of years later, I finally understood what export would actually have given us, and what not... and now I wholeheartedly agree with the EDG people: It would not have brought us what most people (myself in '11 included) think it would, and the C++ standard is better off without it.
    – DevSolar
    Nov 19 '15 at 10:27








  • 1




    @DevSolar : this paper is political, repetitive and badly written. that's not usual standard level prose there. Uneedingly long and boring, saying basically 3 times the same things accross tens of pages. But I am now informed that export is not export. That's a good intel !
    – v.oddou
    Apr 25 '16 at 9:51






  • 1




    @v.oddou: Good developer and good technical writer are two seperate skillsets. Some can do both, many can't. ;-)
    – DevSolar
    Apr 25 '16 at 9:58


















up vote
32
down vote













Although standard C++ has no such requirement, some compilers require that all function and class templates need to be made available in every translation unit they are used. In effect, for those compilers, the bodies of template functions must be made available in a header file. To repeat: that means those compilers won't allow them to be defined in non-header files such as .cpp files



There is an export keyword which is supposed to mitigate this problem, but it's nowhere close to being portable.






share|improve this answer























  • Why can't I implement them in .cpp file with the keyword "inline"?
    – MainID
    Jan 30 '09 at 10:20






  • 2




    You can, and you don't have to put "inline" even. But you'd be able to use them just in that cpp file and nowhere else.
    – vava
    Jan 30 '09 at 10:28






  • 8




    This is almost the most accurate answer, except "that means those compilers won't allow them to be defined in non-header files such as .cpp files" is patently false.
    – Lightness Races in Orbit
    Aug 14 '11 at 17:59




















up vote
26
down vote













Templates must be used in headers because the compiler needs to instantiate different versions of the code, depending on the parameters given/deduced for template parameters. Remember that a template doesn't represent code directly, but a template for several versions of that code.
When you compile a non-template function in a .cpp file, you are compiling a concrete function/class. This is not the case for templates, which can be instantiated with different types, namely, concrete code must be emitted when replacing template parameters with concrete types.



There was a feature with the export keyword that was meant to be used for separate compilation.
The export feature is deprecated in C++11 and, AFAIK, only one compiler implemented it. You shouldn't make use of export. Separate compilation is not possible in C++ or C++11 but maybe in C++17, if concepts make it in, we could have some way of separate compilation.



For separate compilation to be achieved, separate template body checking must be possible. It seems that a solution is possible with concepts. Take a look at this paper recently presented at the
standards commitee meeting. I think this is not the only requirement, since you still need to instantiate code for the template code in user code.



The separate compilation problem for templates I guess it's also a problem that is arising with the migration to modules, which is currently being worked.






share|improve this answer






























    up vote
    13
    down vote













    It means that the most portable way to define method implementations of template classes is to define them inside the template class definition.



    template < typename ... >
    class MyClass
    {

    int myMethod()
    {
    // Not just declaration. Add method implementation here
    }
    };





    share|improve this answer






























      up vote
      9
      down vote













      Even though there are plenty of good explanations above, I'm missing a practical way to separate templates into header and body.

      My main concern is avoiding recompilation of all template users, when I change its definition.

      Having all template instantiations in the template body is not a viable solution for me, since the template author may not know all if its usage and the template user may not have the right to modify it.

      I took the following approach, which works also for older compilers (gcc 4.3.4, aCC A.03.13).



      For each template usage there's a typedef in its own header file (generated from the UML model). Its body contains the instantiation (which ends up in a library which is linked in at the end).

      Each user of the template includes that header file and uses the typedef.



      A schematic example:



      MyTemplate.h:



      #ifndef MyTemplate_h
      #define MyTemplate_h 1

      template <class T>
      class MyTemplate
      {
      public:
      MyTemplate(const T& rt);
      void dump();
      T t;
      };

      #endif


      MyTemplate.cpp:



      #include "MyTemplate.h"
      #include <iostream>

      template <class T>
      MyTemplate<T>::MyTemplate(const T& rt)
      : t(rt)
      {
      }

      template <class T>
      void MyTemplate<T>::dump()
      {
      cerr << t << endl;
      }


      MyInstantiatedTemplate.h:



      #ifndef MyInstantiatedTemplate_h
      #define MyInstantiatedTemplate_h 1
      #include "MyTemplate.h"

      typedef MyTemplate< int > MyInstantiatedTemplate;

      #endif


      MyInstantiatedTemplate.cpp:



      #include "MyTemplate.cpp"

      template class MyTemplate< int >;


      main.cpp:



      #include "MyInstantiatedTemplate.h"

      int main()
      {
      MyInstantiatedTemplate m(100);
      m.dump();
      return 0;
      }


      This way only the template instantiations will need to be recompiled, not all template users (and dependencies).






      share|improve this answer






























        up vote
        6
        down vote













        That is exactly correct because the compiler has to know what type it is for allocation. So template classes, functions, enums,etc.. must be implemented as well in the header file if it is to be made public or part of a library (static or dynamic) because header files are NOT compiled unlike the c/cpp files which are. If the compiler doesn't know the type is can't compile it. In .Net it can because all objects derive from the Object class. This is not .Net.






        share|improve this answer



















        • 5




          "header files are NOT compiled" - that's a really odd way of describing it. Header files can be part of a translation unit, just like a "c/cpp" file.
          – Flexo
          Sep 17 '11 at 12:26






        • 1




          In fact, it's almost the opposite of the truth, which is that header files are very frequently compiled many times, whereas a source file is usually compiled once.
          – xaxxon
          Dec 21 '15 at 22:46


















        up vote
        6
        down vote













        If the concern is the extra compilation time and binary size bloat produced by compiling the .h as part of all the .cpp modules using it, in many cases what you can do is make the template class descend from a non-templatized base class for non type-dependent parts of the interface, and that base class can have its implementation in the .cpp file.






        share|improve this answer

















        • 1




          This response should be modded up quite more. I "independently" discovered your same approach and was specifically looking for somebody else to have used it already, since I'm curious if it's an official pattern and whether it's got a name. My approach is to implement a class XBase wherever I need to implement a template class X, putting the type-dependent parts in X and all the rest in XBase.
          – Fabio A.
          Nov 4 '16 at 8:38




















        up vote
        2
        down vote













        A way to have separate implementation is as follows.



        //inner_foo.h

        template <typename T>
        struct Foo
        {
        void doSomething(T param);
        };


        //foo.tpp
        #include "inner_foo.h"
        template <typename T>
        void Foo<T>::doSomething(T param)
        {
        //implementation
        }


        //foo.h
        #include <foo.tpp>

        //main.cpp
        #include <foo.h>


        inner_foo has the forward declarations. foo.tpp has the implementation and include inner_foo.h; and foo.h will have just one line, to include foo.tpp.



        On compile time, contents of foo.h are copied to foo.tpp and then the whole file is copied to foo.h after which it compiles. This way, there is no limitations, and the naming is consistent, in exchange for one extra file.



        I do this because static analyzers for the code break when it does not see the forward declarations of class in *.tpp. This is annoying when writing code in any IDE or using YouCompleteMe or others.






        share|improve this answer




























          up vote
          1
          down vote













          The compiler will generate code for each template instantiation when you use a template during the compilation step.
          In the compilation and linking process .cpp files are converted to pure object or machine code which in them contains references or undefined symbols because the .h files that are included in your main.cpp have no implementation YET. These are ready to be linked with another object file that defines an implementation for your template and thus you have a full a.out executable.
          However since templates need to be processed in the compilation step in order to generate code for each template instantiation that you do in your main program, linking won't help because compiling the main.cpp into main.o and then compiling your template .cpp into template.o and then linking won't achieve the templates purpose because I'm linking different template instantiation to the same template implementation! And templates are supposed to do the opposite i.e to have ONE implementation but allow many available instantiations via the use of one class.



          Meaning typename T get's replaced during the compilation step not the linking step so if I try to compile a template without T being replaced as a concrete value type so it won't work because that's the definition of templates it's a compile time process, and btw meta-programming is all about using this definition.






          share|improve this answer






























            up vote
            1
            down vote













            Just to add something noteworthy here. One can define methods of a templated class just fine in the implementation file when they are not function templates.





            myQueue.hpp:



            template <class T> 
            class QueueA {
            int size;
            ...
            public:
            template <class T> T dequeue() {
            // implementation here
            }

            bool isEmpty();

            ...
            }




            myQueue.cpp:



            // implementation of regular methods goes like this:
            template <class T> bool QueueA<T>::isEmpty() {
            return this->size == 0;
            }


            main()
            {
            QueueA<char> Q;

            ...
            }





            share|improve this answer




















              protected by Marco A. Oct 15 '14 at 23:24



              Thank you for your interest in this question.
              Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).



              Would you like to answer one of these unanswered questions instead?














              14 Answers
              14






              active

              oldest

              votes








              14 Answers
              14






              active

              oldest

              votes









              active

              oldest

              votes






              active

              oldest

              votes








              up vote
              1266
              down vote



              accepted










              It is not necessary to put the implementation in the header file, see the alternative solution at the end of this answer.



              Anyway, the reason your code is failing is that, when instantiating a template, the compiler creates a new class with the given template argument. For example:



              template<typename T>
              struct Foo
              {
              T bar;
              void doSomething(T param) {/* do stuff using T */}
              };

              // somewhere in a .cpp
              Foo<int> f;


              When reading this line, the compiler will create a new class (let's call it FooInt), which is equivalent to the following:



              struct FooInt
              {
              int bar;
              void doSomething(int param) {/* do stuff using int */}
              }


              Consequently, the compiler needs to have access to the implementation of the methods, to instantiate them with the template argument (in this case int). If these implementations were not in the header, they wouldn't be accessible, and therefore the compiler wouldn't be able to instantiate the template.



              A common solution to this is to write the template declaration in a header file, then implement the class in an implementation file (for example .tpp), and include this implementation file at the end of the header.



              // Foo.h
              template <typename T>
              struct Foo
              {
              void doSomething(T param);
              };

              #include "Foo.tpp"

              // Foo.tpp
              template <typename T>
              void Foo<T>::doSomething(T param)
              {
              //implementation
              }


              This way, implementation is still separated from declaration, but is accessible to the compiler.



              Another solution is to keep the implementation separated, and explicitly instantiate all the template instances you'll need:



              // Foo.h

              // no implementation
              template <typename T> struct Foo { ... };

              //----------------------------------------
              // Foo.cpp

              // implementation of Foo's methods

              // explicit instantiations
              template class Foo<int>;
              template class Foo<float>;
              // You will only be able to use Foo with int or float


              If my explanation isn't clear enough, you can have a look at the C++ Super-FAQ on this subject.






              share|improve this answer



















              • 68




                Actually the explicit instantiation needs to be in a .cpp file which has access to the definitions for all of Foo's member functions, rather than in the header.
                – Mankarse
                May 28 '11 at 10:21








              • 9




                "the compiler needs to have access to the implementation of the methods, to instantiate them with the template argument (in this case int). If these implementations were not in the header, they wouldn't be accessible" But why is an implementation in the .cpp file not accessible to the compiler? A compiler can also access .cpp information, how else would it turn them into .obj files? EDIT: answer to this question is in the link provided in this answer...
                – xcrypt
                Jan 14 '12 at 23:56








              • 25




                I don't think this explains the question that clearly, the key thing is obviously related with the compilation UNIT which is not mentioned in this post
                – zinking
                Aug 23 '12 at 9:47






              • 4




                @Gabson: structs and classes are equivalent with the exception that the default access modifier for classes is "private", while it is public for structs. There are some other tiny differences that you can learn by looking at this question.
                – Luc Touraille
                Feb 21 '14 at 14:12






              • 1




                Use explicit instantiation otherwise you will get very slow builds soon..
                – Nils
                Jul 14 '14 at 13:43















              up vote
              1266
              down vote



              accepted










              It is not necessary to put the implementation in the header file, see the alternative solution at the end of this answer.



              Anyway, the reason your code is failing is that, when instantiating a template, the compiler creates a new class with the given template argument. For example:



              template<typename T>
              struct Foo
              {
              T bar;
              void doSomething(T param) {/* do stuff using T */}
              };

              // somewhere in a .cpp
              Foo<int> f;


              When reading this line, the compiler will create a new class (let's call it FooInt), which is equivalent to the following:



              struct FooInt
              {
              int bar;
              void doSomething(int param) {/* do stuff using int */}
              }


              Consequently, the compiler needs to have access to the implementation of the methods, to instantiate them with the template argument (in this case int). If these implementations were not in the header, they wouldn't be accessible, and therefore the compiler wouldn't be able to instantiate the template.



              A common solution to this is to write the template declaration in a header file, then implement the class in an implementation file (for example .tpp), and include this implementation file at the end of the header.



              // Foo.h
              template <typename T>
              struct Foo
              {
              void doSomething(T param);
              };

              #include "Foo.tpp"

              // Foo.tpp
              template <typename T>
              void Foo<T>::doSomething(T param)
              {
              //implementation
              }


              This way, implementation is still separated from declaration, but is accessible to the compiler.



              Another solution is to keep the implementation separated, and explicitly instantiate all the template instances you'll need:



              // Foo.h

              // no implementation
              template <typename T> struct Foo { ... };

              //----------------------------------------
              // Foo.cpp

              // implementation of Foo's methods

              // explicit instantiations
              template class Foo<int>;
              template class Foo<float>;
              // You will only be able to use Foo with int or float


              If my explanation isn't clear enough, you can have a look at the C++ Super-FAQ on this subject.






              share|improve this answer



















              • 68




                Actually the explicit instantiation needs to be in a .cpp file which has access to the definitions for all of Foo's member functions, rather than in the header.
                – Mankarse
                May 28 '11 at 10:21








              • 9




                "the compiler needs to have access to the implementation of the methods, to instantiate them with the template argument (in this case int). If these implementations were not in the header, they wouldn't be accessible" But why is an implementation in the .cpp file not accessible to the compiler? A compiler can also access .cpp information, how else would it turn them into .obj files? EDIT: answer to this question is in the link provided in this answer...
                – xcrypt
                Jan 14 '12 at 23:56








              • 25




                I don't think this explains the question that clearly, the key thing is obviously related with the compilation UNIT which is not mentioned in this post
                – zinking
                Aug 23 '12 at 9:47






              • 4




                @Gabson: structs and classes are equivalent with the exception that the default access modifier for classes is "private", while it is public for structs. There are some other tiny differences that you can learn by looking at this question.
                – Luc Touraille
                Feb 21 '14 at 14:12






              • 1




                Use explicit instantiation otherwise you will get very slow builds soon..
                – Nils
                Jul 14 '14 at 13:43













              up vote
              1266
              down vote



              accepted







              up vote
              1266
              down vote



              accepted






              It is not necessary to put the implementation in the header file, see the alternative solution at the end of this answer.



              Anyway, the reason your code is failing is that, when instantiating a template, the compiler creates a new class with the given template argument. For example:



              template<typename T>
              struct Foo
              {
              T bar;
              void doSomething(T param) {/* do stuff using T */}
              };

              // somewhere in a .cpp
              Foo<int> f;


              When reading this line, the compiler will create a new class (let's call it FooInt), which is equivalent to the following:



              struct FooInt
              {
              int bar;
              void doSomething(int param) {/* do stuff using int */}
              }


              Consequently, the compiler needs to have access to the implementation of the methods, to instantiate them with the template argument (in this case int). If these implementations were not in the header, they wouldn't be accessible, and therefore the compiler wouldn't be able to instantiate the template.



              A common solution to this is to write the template declaration in a header file, then implement the class in an implementation file (for example .tpp), and include this implementation file at the end of the header.



              // Foo.h
              template <typename T>
              struct Foo
              {
              void doSomething(T param);
              };

              #include "Foo.tpp"

              // Foo.tpp
              template <typename T>
              void Foo<T>::doSomething(T param)
              {
              //implementation
              }


              This way, implementation is still separated from declaration, but is accessible to the compiler.



              Another solution is to keep the implementation separated, and explicitly instantiate all the template instances you'll need:



              // Foo.h

              // no implementation
              template <typename T> struct Foo { ... };

              //----------------------------------------
              // Foo.cpp

              // implementation of Foo's methods

              // explicit instantiations
              template class Foo<int>;
              template class Foo<float>;
              // You will only be able to use Foo with int or float


              If my explanation isn't clear enough, you can have a look at the C++ Super-FAQ on this subject.






              share|improve this answer














              It is not necessary to put the implementation in the header file, see the alternative solution at the end of this answer.



              Anyway, the reason your code is failing is that, when instantiating a template, the compiler creates a new class with the given template argument. For example:



              template<typename T>
              struct Foo
              {
              T bar;
              void doSomething(T param) {/* do stuff using T */}
              };

              // somewhere in a .cpp
              Foo<int> f;


              When reading this line, the compiler will create a new class (let's call it FooInt), which is equivalent to the following:



              struct FooInt
              {
              int bar;
              void doSomething(int param) {/* do stuff using int */}
              }


              Consequently, the compiler needs to have access to the implementation of the methods, to instantiate them with the template argument (in this case int). If these implementations were not in the header, they wouldn't be accessible, and therefore the compiler wouldn't be able to instantiate the template.



              A common solution to this is to write the template declaration in a header file, then implement the class in an implementation file (for example .tpp), and include this implementation file at the end of the header.



              // Foo.h
              template <typename T>
              struct Foo
              {
              void doSomething(T param);
              };

              #include "Foo.tpp"

              // Foo.tpp
              template <typename T>
              void Foo<T>::doSomething(T param)
              {
              //implementation
              }


              This way, implementation is still separated from declaration, but is accessible to the compiler.



              Another solution is to keep the implementation separated, and explicitly instantiate all the template instances you'll need:



              // Foo.h

              // no implementation
              template <typename T> struct Foo { ... };

              //----------------------------------------
              // Foo.cpp

              // implementation of Foo's methods

              // explicit instantiations
              template class Foo<int>;
              template class Foo<float>;
              // You will only be able to use Foo with int or float


              If my explanation isn't clear enough, you can have a look at the C++ Super-FAQ on this subject.







              share|improve this answer














              share|improve this answer



              share|improve this answer








              edited Aug 7 at 13:06









              milleniumbug

              12.5k23362




              12.5k23362










              answered Jan 30 '09 at 10:26









              Luc Touraille

              58.8k1170127




              58.8k1170127








              • 68




                Actually the explicit instantiation needs to be in a .cpp file which has access to the definitions for all of Foo's member functions, rather than in the header.
                – Mankarse
                May 28 '11 at 10:21








              • 9




                "the compiler needs to have access to the implementation of the methods, to instantiate them with the template argument (in this case int). If these implementations were not in the header, they wouldn't be accessible" But why is an implementation in the .cpp file not accessible to the compiler? A compiler can also access .cpp information, how else would it turn them into .obj files? EDIT: answer to this question is in the link provided in this answer...
                – xcrypt
                Jan 14 '12 at 23:56








              • 25




                I don't think this explains the question that clearly, the key thing is obviously related with the compilation UNIT which is not mentioned in this post
                – zinking
                Aug 23 '12 at 9:47






              • 4




                @Gabson: structs and classes are equivalent with the exception that the default access modifier for classes is "private", while it is public for structs. There are some other tiny differences that you can learn by looking at this question.
                – Luc Touraille
                Feb 21 '14 at 14:12






              • 1




                Use explicit instantiation otherwise you will get very slow builds soon..
                – Nils
                Jul 14 '14 at 13:43














              • 68




                Actually the explicit instantiation needs to be in a .cpp file which has access to the definitions for all of Foo's member functions, rather than in the header.
                – Mankarse
                May 28 '11 at 10:21








              • 9




                "the compiler needs to have access to the implementation of the methods, to instantiate them with the template argument (in this case int). If these implementations were not in the header, they wouldn't be accessible" But why is an implementation in the .cpp file not accessible to the compiler? A compiler can also access .cpp information, how else would it turn them into .obj files? EDIT: answer to this question is in the link provided in this answer...
                – xcrypt
                Jan 14 '12 at 23:56








              • 25




                I don't think this explains the question that clearly, the key thing is obviously related with the compilation UNIT which is not mentioned in this post
                – zinking
                Aug 23 '12 at 9:47






              • 4




                @Gabson: structs and classes are equivalent with the exception that the default access modifier for classes is "private", while it is public for structs. There are some other tiny differences that you can learn by looking at this question.
                – Luc Touraille
                Feb 21 '14 at 14:12






              • 1




                Use explicit instantiation otherwise you will get very slow builds soon..
                – Nils
                Jul 14 '14 at 13:43








              68




              68




              Actually the explicit instantiation needs to be in a .cpp file which has access to the definitions for all of Foo's member functions, rather than in the header.
              – Mankarse
              May 28 '11 at 10:21






              Actually the explicit instantiation needs to be in a .cpp file which has access to the definitions for all of Foo's member functions, rather than in the header.
              – Mankarse
              May 28 '11 at 10:21






              9




              9




              "the compiler needs to have access to the implementation of the methods, to instantiate them with the template argument (in this case int). If these implementations were not in the header, they wouldn't be accessible" But why is an implementation in the .cpp file not accessible to the compiler? A compiler can also access .cpp information, how else would it turn them into .obj files? EDIT: answer to this question is in the link provided in this answer...
              – xcrypt
              Jan 14 '12 at 23:56






              "the compiler needs to have access to the implementation of the methods, to instantiate them with the template argument (in this case int). If these implementations were not in the header, they wouldn't be accessible" But why is an implementation in the .cpp file not accessible to the compiler? A compiler can also access .cpp information, how else would it turn them into .obj files? EDIT: answer to this question is in the link provided in this answer...
              – xcrypt
              Jan 14 '12 at 23:56






              25




              25




              I don't think this explains the question that clearly, the key thing is obviously related with the compilation UNIT which is not mentioned in this post
              – zinking
              Aug 23 '12 at 9:47




              I don't think this explains the question that clearly, the key thing is obviously related with the compilation UNIT which is not mentioned in this post
              – zinking
              Aug 23 '12 at 9:47




              4




              4




              @Gabson: structs and classes are equivalent with the exception that the default access modifier for classes is "private", while it is public for structs. There are some other tiny differences that you can learn by looking at this question.
              – Luc Touraille
              Feb 21 '14 at 14:12




              @Gabson: structs and classes are equivalent with the exception that the default access modifier for classes is "private", while it is public for structs. There are some other tiny differences that you can learn by looking at this question.
              – Luc Touraille
              Feb 21 '14 at 14:12




              1




              1




              Use explicit instantiation otherwise you will get very slow builds soon..
              – Nils
              Jul 14 '14 at 13:43




              Use explicit instantiation otherwise you will get very slow builds soon..
              – Nils
              Jul 14 '14 at 13:43












              up vote
              209
              down vote













              Plenty correct answers here, but I wanted to add this (for completeness):



              If you, at the bottom of the implementation cpp file, do explicit instantiation of all the types the template will be used with, the linker will be able to find them as usual.



              Edit: Adding example of explicit template instantiation. Used after the template has been defined, and all member functions has been defined.



              template class vector<int>;


              This will instantiate (and thus make available to the linker) the class and all its member functions (only). Similar syntax works for template functions, so if you have non-member operator overloads you may need to do the same for those.



              The above example is fairly useless since vector is fully defined in headers, except when a common include file (precompiled header?) uses extern template class vector<int> so as to keep it from instantiating it in all the other (1000?) files that use vector.






              share|improve this answer



















              • 32




                Ugh. Good answer, but no real clean solution. Listing out all possible types for a template does not seem to go with what a template is supposed to be.
                – Jiminion
                Jul 17 '14 at 17:49






              • 5




                This can be good in many cases but generally breaks the purpose of template which is meant to allow you to use the class with any type without manually listing them.
                – Tomáš Zato
                Dec 9 '14 at 3:27








              • 4




                vector is not a good example because a container is inherently targeting "all" types. But it does happen very frequently that you create templates that are only meant for a specific set of types, for instance numeric types: int8_t, int16_t, int32_t, uint8_t, uint16_t, etc. In this case, it still makes sense to use a template, but explicitly instantiating them for the whole set of types is also possible and, in my opinion, recommended.
                – UncleZeiv
                Jun 3 '15 at 15:41










              • Used after the template has been defined, "and all member functions has been defined". Thanks !
                – Vitt Volt
                Feb 16 '17 at 6:04












              • I'd like to know, is it possible to do the explicit instantiations from somewhere other than the class' header or source file? For instance, do them in main.cpp?
                – gromit190
                Mar 9 '17 at 8:01















              up vote
              209
              down vote













              Plenty correct answers here, but I wanted to add this (for completeness):



              If you, at the bottom of the implementation cpp file, do explicit instantiation of all the types the template will be used with, the linker will be able to find them as usual.



              Edit: Adding example of explicit template instantiation. Used after the template has been defined, and all member functions has been defined.



              template class vector<int>;


              This will instantiate (and thus make available to the linker) the class and all its member functions (only). Similar syntax works for template functions, so if you have non-member operator overloads you may need to do the same for those.



              The above example is fairly useless since vector is fully defined in headers, except when a common include file (precompiled header?) uses extern template class vector<int> so as to keep it from instantiating it in all the other (1000?) files that use vector.






              share|improve this answer



















              • 32




                Ugh. Good answer, but no real clean solution. Listing out all possible types for a template does not seem to go with what a template is supposed to be.
                – Jiminion
                Jul 17 '14 at 17:49






              • 5




                This can be good in many cases but generally breaks the purpose of template which is meant to allow you to use the class with any type without manually listing them.
                – Tomáš Zato
                Dec 9 '14 at 3:27








              • 4




                vector is not a good example because a container is inherently targeting "all" types. But it does happen very frequently that you create templates that are only meant for a specific set of types, for instance numeric types: int8_t, int16_t, int32_t, uint8_t, uint16_t, etc. In this case, it still makes sense to use a template, but explicitly instantiating them for the whole set of types is also possible and, in my opinion, recommended.
                – UncleZeiv
                Jun 3 '15 at 15:41










              • Used after the template has been defined, "and all member functions has been defined". Thanks !
                – Vitt Volt
                Feb 16 '17 at 6:04












              • I'd like to know, is it possible to do the explicit instantiations from somewhere other than the class' header or source file? For instance, do them in main.cpp?
                – gromit190
                Mar 9 '17 at 8:01













              up vote
              209
              down vote










              up vote
              209
              down vote









              Plenty correct answers here, but I wanted to add this (for completeness):



              If you, at the bottom of the implementation cpp file, do explicit instantiation of all the types the template will be used with, the linker will be able to find them as usual.



              Edit: Adding example of explicit template instantiation. Used after the template has been defined, and all member functions has been defined.



              template class vector<int>;


              This will instantiate (and thus make available to the linker) the class and all its member functions (only). Similar syntax works for template functions, so if you have non-member operator overloads you may need to do the same for those.



              The above example is fairly useless since vector is fully defined in headers, except when a common include file (precompiled header?) uses extern template class vector<int> so as to keep it from instantiating it in all the other (1000?) files that use vector.






              share|improve this answer














              Plenty correct answers here, but I wanted to add this (for completeness):



              If you, at the bottom of the implementation cpp file, do explicit instantiation of all the types the template will be used with, the linker will be able to find them as usual.



              Edit: Adding example of explicit template instantiation. Used after the template has been defined, and all member functions has been defined.



              template class vector<int>;


              This will instantiate (and thus make available to the linker) the class and all its member functions (only). Similar syntax works for template functions, so if you have non-member operator overloads you may need to do the same for those.



              The above example is fairly useless since vector is fully defined in headers, except when a common include file (precompiled header?) uses extern template class vector<int> so as to keep it from instantiating it in all the other (1000?) files that use vector.







              share|improve this answer














              share|improve this answer



              share|improve this answer








              edited Feb 14 '13 at 14:26









              Jonathan Wakely

              129k15236399




              129k15236399










              answered Aug 13 '09 at 13:49









              MaHuJa

              2,4301126




              2,4301126








              • 32




                Ugh. Good answer, but no real clean solution. Listing out all possible types for a template does not seem to go with what a template is supposed to be.
                – Jiminion
                Jul 17 '14 at 17:49






              • 5




                This can be good in many cases but generally breaks the purpose of template which is meant to allow you to use the class with any type without manually listing them.
                – Tomáš Zato
                Dec 9 '14 at 3:27








              • 4




                vector is not a good example because a container is inherently targeting "all" types. But it does happen very frequently that you create templates that are only meant for a specific set of types, for instance numeric types: int8_t, int16_t, int32_t, uint8_t, uint16_t, etc. In this case, it still makes sense to use a template, but explicitly instantiating them for the whole set of types is also possible and, in my opinion, recommended.
                – UncleZeiv
                Jun 3 '15 at 15:41










              • Used after the template has been defined, "and all member functions has been defined". Thanks !
                – Vitt Volt
                Feb 16 '17 at 6:04












              • I'd like to know, is it possible to do the explicit instantiations from somewhere other than the class' header or source file? For instance, do them in main.cpp?
                – gromit190
                Mar 9 '17 at 8:01














              • 32




                Ugh. Good answer, but no real clean solution. Listing out all possible types for a template does not seem to go with what a template is supposed to be.
                – Jiminion
                Jul 17 '14 at 17:49






              • 5




                This can be good in many cases but generally breaks the purpose of template which is meant to allow you to use the class with any type without manually listing them.
                – Tomáš Zato
                Dec 9 '14 at 3:27








              • 4




                vector is not a good example because a container is inherently targeting "all" types. But it does happen very frequently that you create templates that are only meant for a specific set of types, for instance numeric types: int8_t, int16_t, int32_t, uint8_t, uint16_t, etc. In this case, it still makes sense to use a template, but explicitly instantiating them for the whole set of types is also possible and, in my opinion, recommended.
                – UncleZeiv
                Jun 3 '15 at 15:41










              • Used after the template has been defined, "and all member functions has been defined". Thanks !
                – Vitt Volt
                Feb 16 '17 at 6:04












              • I'd like to know, is it possible to do the explicit instantiations from somewhere other than the class' header or source file? For instance, do them in main.cpp?
                – gromit190
                Mar 9 '17 at 8:01








              32




              32




              Ugh. Good answer, but no real clean solution. Listing out all possible types for a template does not seem to go with what a template is supposed to be.
              – Jiminion
              Jul 17 '14 at 17:49




              Ugh. Good answer, but no real clean solution. Listing out all possible types for a template does not seem to go with what a template is supposed to be.
              – Jiminion
              Jul 17 '14 at 17:49




              5




              5




              This can be good in many cases but generally breaks the purpose of template which is meant to allow you to use the class with any type without manually listing them.
              – Tomáš Zato
              Dec 9 '14 at 3:27






              This can be good in many cases but generally breaks the purpose of template which is meant to allow you to use the class with any type without manually listing them.
              – Tomáš Zato
              Dec 9 '14 at 3:27






              4




              4




              vector is not a good example because a container is inherently targeting "all" types. But it does happen very frequently that you create templates that are only meant for a specific set of types, for instance numeric types: int8_t, int16_t, int32_t, uint8_t, uint16_t, etc. In this case, it still makes sense to use a template, but explicitly instantiating them for the whole set of types is also possible and, in my opinion, recommended.
              – UncleZeiv
              Jun 3 '15 at 15:41




              vector is not a good example because a container is inherently targeting "all" types. But it does happen very frequently that you create templates that are only meant for a specific set of types, for instance numeric types: int8_t, int16_t, int32_t, uint8_t, uint16_t, etc. In this case, it still makes sense to use a template, but explicitly instantiating them for the whole set of types is also possible and, in my opinion, recommended.
              – UncleZeiv
              Jun 3 '15 at 15:41












              Used after the template has been defined, "and all member functions has been defined". Thanks !
              – Vitt Volt
              Feb 16 '17 at 6:04






              Used after the template has been defined, "and all member functions has been defined". Thanks !
              – Vitt Volt
              Feb 16 '17 at 6:04














              I'd like to know, is it possible to do the explicit instantiations from somewhere other than the class' header or source file? For instance, do them in main.cpp?
              – gromit190
              Mar 9 '17 at 8:01




              I'd like to know, is it possible to do the explicit instantiations from somewhere other than the class' header or source file? For instance, do them in main.cpp?
              – gromit190
              Mar 9 '17 at 8:01










              up vote
              185
              down vote













              It's because of the requirement for separate compilation and because templates are instantiation-style polymorphism.



              Lets get a little closer to concrete for an explanation. Say I've got the following files:




              • foo.h

                • declares the interface of class MyClass<T>



              • foo.cpp

                • defines the implementation of class MyClass<T>



              • bar.cpp

                • uses MyClass<int>




              Separate compilation means I should be able to compile foo.cpp independently from bar.cpp. The compiler does all the hard work of analysis, optimization, and code generation on each compilation unit completely independently; we don't need to do whole-program analysis. It's only the linker that needs to handle the entire program at once, and the linker's job is substantially easier.



              bar.cpp doesn't even need to exist when I compile foo.cpp, but I should still be able to link the foo.o I already had together with the bar.o I've only just produced, without needing to recompile foo.cpp. foo.cpp could even be compiled into a dynamic library, distributed somewhere else without foo.cpp, and linked with code they write years after I wrote foo.cpp.



              "Instantiation-style polymorphism" means that the template MyClass<T> isn't really a generic class that can be compiled to code that can work for any value of T. That would add overhead such as boxing, needing to pass function pointers to allocators and constructors, etc. The intention of C++ templates is to avoid having to write nearly identical class MyClass_int, class MyClass_float, etc, but to still be able to end up with compiled code that is mostly as if we had written each version separately. So a template is literally a template; a class template is not a class, it's a recipe for creating a new class for each T we encounter. A template cannot be compiled into code, only the result of instantiating the template can be compiled.



              So when foo.cpp is compiled, the compiler can't see bar.cpp to know that MyClass<int> is needed. It can see the template MyClass<T>, but it can't emit code for that (it's a template, not a class). And when bar.cpp is compiled, the compiler can see that it needs to create a MyClass<int>, but it can't see the template MyClass<T> (only its interface in foo.h) so it can't create it.



              If foo.cpp itself uses MyClass<int>, then code for that will be generated while compiling foo.cpp, so when bar.o is linked to foo.o they can be hooked up and will work. We can use that fact to allow a finite set of template instantiations to be implemented in a .cpp file by writing a single template. But there's no way for bar.cpp to use the template as a template and instantiate it on whatever types it likes; it can only use pre-existing versions of the templated class that the author of foo.cpp thought to provide.



              You might think that when compiling a template the compiler should "generate all versions", with the ones that are never used being filtered out during linking. Aside from the huge overhead and the extreme difficulties such an approach would face because "type modifier" features like pointers and arrays allow even just the built-in types to give rise to an infinite number of types, what happens when I now extend my program by adding:




              • baz.cpp

                • declares and implements class BazPrivate, and uses MyClass<BazPrivate>




              There is no possible way that this could work unless we either




              1. Have to recompile foo.cpp every time we change any other file in the program, in case it added a new novel instantiation of MyClass<T>

              2. Require that baz.cpp contains (possibly via header includes) the full template of MyClass<T>, so that the compiler can generate MyClass<BazPrivate> during compilation of baz.cpp.


              Nobody likes (1), because whole-program-analysis compilation systems take forever to compile , and because it makes it impossible to distribute compiled libraries without the source code. So we have (2) instead.






              share|improve this answer



















              • 26




                emphasized quote a template is literally a template; a class template is not a class, it's a recipe for creating a new class for each T we encounter
                – v.oddou
                Apr 25 '16 at 9:57










              • I'd like to know, is it possible to do the explicit instantiations from somewhere other than the class' header or source file? For instance, do them in main.cpp?
                – gromit190
                Mar 9 '17 at 8:01






              • 1




                @Birger You should be able to do it from any file that has access to the full template implementation (either because it's in the same file or via header includes).
                – Ben
                Mar 9 '17 at 11:02










              • How's this an answer? It provides no solution but rhetoric only.
                – ajeh
                Apr 2 at 18:48






              • 4




                @ajeh It's not rhetoric. The question is "why do you have to implement templates in a header?", so I explained the technical choices the C++ language makes that lead to this requirement. Before I wrote my answer others already provided workarounds that are not full solutions, because there can't be a full solution. I felt those answers would be complemented by a fuller discussion of the "why" angle of the question.
                – Ben
                Apr 2 at 22:02















              up vote
              185
              down vote













              It's because of the requirement for separate compilation and because templates are instantiation-style polymorphism.



              Lets get a little closer to concrete for an explanation. Say I've got the following files:




              • foo.h

                • declares the interface of class MyClass<T>



              • foo.cpp

                • defines the implementation of class MyClass<T>



              • bar.cpp

                • uses MyClass<int>




              Separate compilation means I should be able to compile foo.cpp independently from bar.cpp. The compiler does all the hard work of analysis, optimization, and code generation on each compilation unit completely independently; we don't need to do whole-program analysis. It's only the linker that needs to handle the entire program at once, and the linker's job is substantially easier.



              bar.cpp doesn't even need to exist when I compile foo.cpp, but I should still be able to link the foo.o I already had together with the bar.o I've only just produced, without needing to recompile foo.cpp. foo.cpp could even be compiled into a dynamic library, distributed somewhere else without foo.cpp, and linked with code they write years after I wrote foo.cpp.



              "Instantiation-style polymorphism" means that the template MyClass<T> isn't really a generic class that can be compiled to code that can work for any value of T. That would add overhead such as boxing, needing to pass function pointers to allocators and constructors, etc. The intention of C++ templates is to avoid having to write nearly identical class MyClass_int, class MyClass_float, etc, but to still be able to end up with compiled code that is mostly as if we had written each version separately. So a template is literally a template; a class template is not a class, it's a recipe for creating a new class for each T we encounter. A template cannot be compiled into code, only the result of instantiating the template can be compiled.



              So when foo.cpp is compiled, the compiler can't see bar.cpp to know that MyClass<int> is needed. It can see the template MyClass<T>, but it can't emit code for that (it's a template, not a class). And when bar.cpp is compiled, the compiler can see that it needs to create a MyClass<int>, but it can't see the template MyClass<T> (only its interface in foo.h) so it can't create it.



              If foo.cpp itself uses MyClass<int>, then code for that will be generated while compiling foo.cpp, so when bar.o is linked to foo.o they can be hooked up and will work. We can use that fact to allow a finite set of template instantiations to be implemented in a .cpp file by writing a single template. But there's no way for bar.cpp to use the template as a template and instantiate it on whatever types it likes; it can only use pre-existing versions of the templated class that the author of foo.cpp thought to provide.



              You might think that when compiling a template the compiler should "generate all versions", with the ones that are never used being filtered out during linking. Aside from the huge overhead and the extreme difficulties such an approach would face because "type modifier" features like pointers and arrays allow even just the built-in types to give rise to an infinite number of types, what happens when I now extend my program by adding:




              • baz.cpp

                • declares and implements class BazPrivate, and uses MyClass<BazPrivate>




              There is no possible way that this could work unless we either




              1. Have to recompile foo.cpp every time we change any other file in the program, in case it added a new novel instantiation of MyClass<T>

              2. Require that baz.cpp contains (possibly via header includes) the full template of MyClass<T>, so that the compiler can generate MyClass<BazPrivate> during compilation of baz.cpp.


              Nobody likes (1), because whole-program-analysis compilation systems take forever to compile , and because it makes it impossible to distribute compiled libraries without the source code. So we have (2) instead.






              share|improve this answer



















              • 26




                emphasized quote a template is literally a template; a class template is not a class, it's a recipe for creating a new class for each T we encounter
                – v.oddou
                Apr 25 '16 at 9:57










              • I'd like to know, is it possible to do the explicit instantiations from somewhere other than the class' header or source file? For instance, do them in main.cpp?
                – gromit190
                Mar 9 '17 at 8:01






              • 1




                @Birger You should be able to do it from any file that has access to the full template implementation (either because it's in the same file or via header includes).
                – Ben
                Mar 9 '17 at 11:02










              • How's this an answer? It provides no solution but rhetoric only.
                – ajeh
                Apr 2 at 18:48






              • 4




                @ajeh It's not rhetoric. The question is "why do you have to implement templates in a header?", so I explained the technical choices the C++ language makes that lead to this requirement. Before I wrote my answer others already provided workarounds that are not full solutions, because there can't be a full solution. I felt those answers would be complemented by a fuller discussion of the "why" angle of the question.
                – Ben
                Apr 2 at 22:02













              up vote
              185
              down vote










              up vote
              185
              down vote









              It's because of the requirement for separate compilation and because templates are instantiation-style polymorphism.



              Lets get a little closer to concrete for an explanation. Say I've got the following files:




              • foo.h

                • declares the interface of class MyClass<T>



              • foo.cpp

                • defines the implementation of class MyClass<T>



              • bar.cpp

                • uses MyClass<int>




              Separate compilation means I should be able to compile foo.cpp independently from bar.cpp. The compiler does all the hard work of analysis, optimization, and code generation on each compilation unit completely independently; we don't need to do whole-program analysis. It's only the linker that needs to handle the entire program at once, and the linker's job is substantially easier.



              bar.cpp doesn't even need to exist when I compile foo.cpp, but I should still be able to link the foo.o I already had together with the bar.o I've only just produced, without needing to recompile foo.cpp. foo.cpp could even be compiled into a dynamic library, distributed somewhere else without foo.cpp, and linked with code they write years after I wrote foo.cpp.



              "Instantiation-style polymorphism" means that the template MyClass<T> isn't really a generic class that can be compiled to code that can work for any value of T. That would add overhead such as boxing, needing to pass function pointers to allocators and constructors, etc. The intention of C++ templates is to avoid having to write nearly identical class MyClass_int, class MyClass_float, etc, but to still be able to end up with compiled code that is mostly as if we had written each version separately. So a template is literally a template; a class template is not a class, it's a recipe for creating a new class for each T we encounter. A template cannot be compiled into code, only the result of instantiating the template can be compiled.



              So when foo.cpp is compiled, the compiler can't see bar.cpp to know that MyClass<int> is needed. It can see the template MyClass<T>, but it can't emit code for that (it's a template, not a class). And when bar.cpp is compiled, the compiler can see that it needs to create a MyClass<int>, but it can't see the template MyClass<T> (only its interface in foo.h) so it can't create it.



              If foo.cpp itself uses MyClass<int>, then code for that will be generated while compiling foo.cpp, so when bar.o is linked to foo.o they can be hooked up and will work. We can use that fact to allow a finite set of template instantiations to be implemented in a .cpp file by writing a single template. But there's no way for bar.cpp to use the template as a template and instantiate it on whatever types it likes; it can only use pre-existing versions of the templated class that the author of foo.cpp thought to provide.



              You might think that when compiling a template the compiler should "generate all versions", with the ones that are never used being filtered out during linking. Aside from the huge overhead and the extreme difficulties such an approach would face because "type modifier" features like pointers and arrays allow even just the built-in types to give rise to an infinite number of types, what happens when I now extend my program by adding:




              • baz.cpp

                • declares and implements class BazPrivate, and uses MyClass<BazPrivate>




              There is no possible way that this could work unless we either




              1. Have to recompile foo.cpp every time we change any other file in the program, in case it added a new novel instantiation of MyClass<T>

              2. Require that baz.cpp contains (possibly via header includes) the full template of MyClass<T>, so that the compiler can generate MyClass<BazPrivate> during compilation of baz.cpp.


              Nobody likes (1), because whole-program-analysis compilation systems take forever to compile , and because it makes it impossible to distribute compiled libraries without the source code. So we have (2) instead.






              share|improve this answer














              It's because of the requirement for separate compilation and because templates are instantiation-style polymorphism.



              Lets get a little closer to concrete for an explanation. Say I've got the following files:




              • foo.h

                • declares the interface of class MyClass<T>



              • foo.cpp

                • defines the implementation of class MyClass<T>



              • bar.cpp

                • uses MyClass<int>




              Separate compilation means I should be able to compile foo.cpp independently from bar.cpp. The compiler does all the hard work of analysis, optimization, and code generation on each compilation unit completely independently; we don't need to do whole-program analysis. It's only the linker that needs to handle the entire program at once, and the linker's job is substantially easier.



              bar.cpp doesn't even need to exist when I compile foo.cpp, but I should still be able to link the foo.o I already had together with the bar.o I've only just produced, without needing to recompile foo.cpp. foo.cpp could even be compiled into a dynamic library, distributed somewhere else without foo.cpp, and linked with code they write years after I wrote foo.cpp.



              "Instantiation-style polymorphism" means that the template MyClass<T> isn't really a generic class that can be compiled to code that can work for any value of T. That would add overhead such as boxing, needing to pass function pointers to allocators and constructors, etc. The intention of C++ templates is to avoid having to write nearly identical class MyClass_int, class MyClass_float, etc, but to still be able to end up with compiled code that is mostly as if we had written each version separately. So a template is literally a template; a class template is not a class, it's a recipe for creating a new class for each T we encounter. A template cannot be compiled into code, only the result of instantiating the template can be compiled.



              So when foo.cpp is compiled, the compiler can't see bar.cpp to know that MyClass<int> is needed. It can see the template MyClass<T>, but it can't emit code for that (it's a template, not a class). And when bar.cpp is compiled, the compiler can see that it needs to create a MyClass<int>, but it can't see the template MyClass<T> (only its interface in foo.h) so it can't create it.



              If foo.cpp itself uses MyClass<int>, then code for that will be generated while compiling foo.cpp, so when bar.o is linked to foo.o they can be hooked up and will work. We can use that fact to allow a finite set of template instantiations to be implemented in a .cpp file by writing a single template. But there's no way for bar.cpp to use the template as a template and instantiate it on whatever types it likes; it can only use pre-existing versions of the templated class that the author of foo.cpp thought to provide.



              You might think that when compiling a template the compiler should "generate all versions", with the ones that are never used being filtered out during linking. Aside from the huge overhead and the extreme difficulties such an approach would face because "type modifier" features like pointers and arrays allow even just the built-in types to give rise to an infinite number of types, what happens when I now extend my program by adding:




              • baz.cpp

                • declares and implements class BazPrivate, and uses MyClass<BazPrivate>




              There is no possible way that this could work unless we either




              1. Have to recompile foo.cpp every time we change any other file in the program, in case it added a new novel instantiation of MyClass<T>

              2. Require that baz.cpp contains (possibly via header includes) the full template of MyClass<T>, so that the compiler can generate MyClass<BazPrivate> during compilation of baz.cpp.


              Nobody likes (1), because whole-program-analysis compilation systems take forever to compile , and because it makes it impossible to distribute compiled libraries without the source code. So we have (2) instead.







              share|improve this answer














              share|improve this answer



              share|improve this answer








              edited May 11 '13 at 11:26

























              answered May 11 '13 at 3:54









              Ben

              45.5k1398138




              45.5k1398138








              • 26




                emphasized quote a template is literally a template; a class template is not a class, it's a recipe for creating a new class for each T we encounter
                – v.oddou
                Apr 25 '16 at 9:57










              • I'd like to know, is it possible to do the explicit instantiations from somewhere other than the class' header or source file? For instance, do them in main.cpp?
                – gromit190
                Mar 9 '17 at 8:01






              • 1




                @Birger You should be able to do it from any file that has access to the full template implementation (either because it's in the same file or via header includes).
                – Ben
                Mar 9 '17 at 11:02










              • How's this an answer? It provides no solution but rhetoric only.
                – ajeh
                Apr 2 at 18:48






              • 4




                @ajeh It's not rhetoric. The question is "why do you have to implement templates in a header?", so I explained the technical choices the C++ language makes that lead to this requirement. Before I wrote my answer others already provided workarounds that are not full solutions, because there can't be a full solution. I felt those answers would be complemented by a fuller discussion of the "why" angle of the question.
                – Ben
                Apr 2 at 22:02














              • 26




                emphasized quote a template is literally a template; a class template is not a class, it's a recipe for creating a new class for each T we encounter
                – v.oddou
                Apr 25 '16 at 9:57










              • I'd like to know, is it possible to do the explicit instantiations from somewhere other than the class' header or source file? For instance, do them in main.cpp?
                – gromit190
                Mar 9 '17 at 8:01






              • 1




                @Birger You should be able to do it from any file that has access to the full template implementation (either because it's in the same file or via header includes).
                – Ben
                Mar 9 '17 at 11:02










              • How's this an answer? It provides no solution but rhetoric only.
                – ajeh
                Apr 2 at 18:48






              • 4




                @ajeh It's not rhetoric. The question is "why do you have to implement templates in a header?", so I explained the technical choices the C++ language makes that lead to this requirement. Before I wrote my answer others already provided workarounds that are not full solutions, because there can't be a full solution. I felt those answers would be complemented by a fuller discussion of the "why" angle of the question.
                – Ben
                Apr 2 at 22:02








              26




              26




              emphasized quote a template is literally a template; a class template is not a class, it's a recipe for creating a new class for each T we encounter
              – v.oddou
              Apr 25 '16 at 9:57




              emphasized quote a template is literally a template; a class template is not a class, it's a recipe for creating a new class for each T we encounter
              – v.oddou
              Apr 25 '16 at 9:57












              I'd like to know, is it possible to do the explicit instantiations from somewhere other than the class' header or source file? For instance, do them in main.cpp?
              – gromit190
              Mar 9 '17 at 8:01




              I'd like to know, is it possible to do the explicit instantiations from somewhere other than the class' header or source file? For instance, do them in main.cpp?
              – gromit190
              Mar 9 '17 at 8:01




              1




              1




              @Birger You should be able to do it from any file that has access to the full template implementation (either because it's in the same file or via header includes).
              – Ben
              Mar 9 '17 at 11:02




              @Birger You should be able to do it from any file that has access to the full template implementation (either because it's in the same file or via header includes).
              – Ben
              Mar 9 '17 at 11:02












              How's this an answer? It provides no solution but rhetoric only.
              – ajeh
              Apr 2 at 18:48




              How's this an answer? It provides no solution but rhetoric only.
              – ajeh
              Apr 2 at 18:48




              4




              4




              @ajeh It's not rhetoric. The question is "why do you have to implement templates in a header?", so I explained the technical choices the C++ language makes that lead to this requirement. Before I wrote my answer others already provided workarounds that are not full solutions, because there can't be a full solution. I felt those answers would be complemented by a fuller discussion of the "why" angle of the question.
              – Ben
              Apr 2 at 22:02




              @ajeh It's not rhetoric. The question is "why do you have to implement templates in a header?", so I explained the technical choices the C++ language makes that lead to this requirement. Before I wrote my answer others already provided workarounds that are not full solutions, because there can't be a full solution. I felt those answers would be complemented by a fuller discussion of the "why" angle of the question.
              – Ben
              Apr 2 at 22:02










              up vote
              67
              down vote













              Templates need to be instantiated by the compiler before actually compiling them into object code. This instantiation can only be achieved if the template arguments are known. Now imagine a scenario where a template function is declared in a.h, defined in a.cpp and used in b.cpp. When a.cpp is compiled, it is not necessarily known that the upcoming compilation b.cpp will require an instance of the template, let alone which specific instance would that be. For more header and source files, the situation can quickly get more complicated.



              One can argue that compilers can be made smarter to "look ahead" for all uses of the template, but I'm sure that it wouldn't be difficult to create recursive or otherwise complicated scenarios. AFAIK, compilers don't do such look aheads. As Anton pointed out, some compilers support explicit export declarations of template instantiations, but not all compilers support it (yet?).






              share|improve this answer



















              • 1




                "export" is standard, but it's just hard to implement so most of the compiler teams just haven't done yet.
                – vava
                Jan 30 '09 at 10:27






              • 5




                export doesn't eliminate the need for source disclosure, nor does it reduce compile dependencies, while it requires a massive effort from compiler builders. So Herb Sutter himself asked compiler builders to 'forget about' export. As the time investment needed would be better spend elsewhere...
                – Pieter
                Jan 30 '09 at 15:13






              • 2




                So I don't think export isn't implemented 'yet'. It'll probably never get done by anyone else than EDG after the others saw how long it took, and how little was gained
                – Pieter
                Jan 30 '09 at 15:14






              • 3




                If that interests you, the paper is called "Why we can't afford export", it's listed on his blog (gotw.ca/publications) but no pdf there (a quick google should turn it up though)
                – Pieter
                Jan 30 '09 at 15:22










              • Ok, thanks for good example and explanation. Here is my question though: why compiler cannot figure out where template is called, and compile those files first before compiling definition file? I can imagine it can be done in a simple case... Is the answer that interdependencies will mess up the order pretty fast?
                – Vlad
                Oct 11 '13 at 17:54















              up vote
              67
              down vote













              Templates need to be instantiated by the compiler before actually compiling them into object code. This instantiation can only be achieved if the template arguments are known. Now imagine a scenario where a template function is declared in a.h, defined in a.cpp and used in b.cpp. When a.cpp is compiled, it is not necessarily known that the upcoming compilation b.cpp will require an instance of the template, let alone which specific instance would that be. For more header and source files, the situation can quickly get more complicated.



              One can argue that compilers can be made smarter to "look ahead" for all uses of the template, but I'm sure that it wouldn't be difficult to create recursive or otherwise complicated scenarios. AFAIK, compilers don't do such look aheads. As Anton pointed out, some compilers support explicit export declarations of template instantiations, but not all compilers support it (yet?).






              share|improve this answer



















              • 1




                "export" is standard, but it's just hard to implement so most of the compiler teams just haven't done yet.
                – vava
                Jan 30 '09 at 10:27






              • 5




                export doesn't eliminate the need for source disclosure, nor does it reduce compile dependencies, while it requires a massive effort from compiler builders. So Herb Sutter himself asked compiler builders to 'forget about' export. As the time investment needed would be better spend elsewhere...
                – Pieter
                Jan 30 '09 at 15:13






              • 2




                So I don't think export isn't implemented 'yet'. It'll probably never get done by anyone else than EDG after the others saw how long it took, and how little was gained
                – Pieter
                Jan 30 '09 at 15:14






              • 3




                If that interests you, the paper is called "Why we can't afford export", it's listed on his blog (gotw.ca/publications) but no pdf there (a quick google should turn it up though)
                – Pieter
                Jan 30 '09 at 15:22










              • Ok, thanks for good example and explanation. Here is my question though: why compiler cannot figure out where template is called, and compile those files first before compiling definition file? I can imagine it can be done in a simple case... Is the answer that interdependencies will mess up the order pretty fast?
                – Vlad
                Oct 11 '13 at 17:54













              up vote
              67
              down vote










              up vote
              67
              down vote









              Templates need to be instantiated by the compiler before actually compiling them into object code. This instantiation can only be achieved if the template arguments are known. Now imagine a scenario where a template function is declared in a.h, defined in a.cpp and used in b.cpp. When a.cpp is compiled, it is not necessarily known that the upcoming compilation b.cpp will require an instance of the template, let alone which specific instance would that be. For more header and source files, the situation can quickly get more complicated.



              One can argue that compilers can be made smarter to "look ahead" for all uses of the template, but I'm sure that it wouldn't be difficult to create recursive or otherwise complicated scenarios. AFAIK, compilers don't do such look aheads. As Anton pointed out, some compilers support explicit export declarations of template instantiations, but not all compilers support it (yet?).






              share|improve this answer














              Templates need to be instantiated by the compiler before actually compiling them into object code. This instantiation can only be achieved if the template arguments are known. Now imagine a scenario where a template function is declared in a.h, defined in a.cpp and used in b.cpp. When a.cpp is compiled, it is not necessarily known that the upcoming compilation b.cpp will require an instance of the template, let alone which specific instance would that be. For more header and source files, the situation can quickly get more complicated.



              One can argue that compilers can be made smarter to "look ahead" for all uses of the template, but I'm sure that it wouldn't be difficult to create recursive or otherwise complicated scenarios. AFAIK, compilers don't do such look aheads. As Anton pointed out, some compilers support explicit export declarations of template instantiations, but not all compilers support it (yet?).







              share|improve this answer














              share|improve this answer



              share|improve this answer








              edited Aug 4 '16 at 7:41









              K DawG

              6,60172257




              6,60172257










              answered Jan 30 '09 at 10:23









              David Hanak

              8,61412537




              8,61412537








              • 1




                "export" is standard, but it's just hard to implement so most of the compiler teams just haven't done yet.
                – vava
                Jan 30 '09 at 10:27






              • 5




                export doesn't eliminate the need for source disclosure, nor does it reduce compile dependencies, while it requires a massive effort from compiler builders. So Herb Sutter himself asked compiler builders to 'forget about' export. As the time investment needed would be better spend elsewhere...
                – Pieter
                Jan 30 '09 at 15:13






              • 2




                So I don't think export isn't implemented 'yet'. It'll probably never get done by anyone else than EDG after the others saw how long it took, and how little was gained
                – Pieter
                Jan 30 '09 at 15:14






              • 3




                If that interests you, the paper is called "Why we can't afford export", it's listed on his blog (gotw.ca/publications) but no pdf there (a quick google should turn it up though)
                – Pieter
                Jan 30 '09 at 15:22










              • Ok, thanks for good example and explanation. Here is my question though: why compiler cannot figure out where template is called, and compile those files first before compiling definition file? I can imagine it can be done in a simple case... Is the answer that interdependencies will mess up the order pretty fast?
                – Vlad
                Oct 11 '13 at 17:54














              • 1




                "export" is standard, but it's just hard to implement so most of the compiler teams just haven't done yet.
                – vava
                Jan 30 '09 at 10:27






              • 5




                export doesn't eliminate the need for source disclosure, nor does it reduce compile dependencies, while it requires a massive effort from compiler builders. So Herb Sutter himself asked compiler builders to 'forget about' export. As the time investment needed would be better spend elsewhere...
                – Pieter
                Jan 30 '09 at 15:13






              • 2




                So I don't think export isn't implemented 'yet'. It'll probably never get done by anyone else than EDG after the others saw how long it took, and how little was gained
                – Pieter
                Jan 30 '09 at 15:14






              • 3




                If that interests you, the paper is called "Why we can't afford export", it's listed on his blog (gotw.ca/publications) but no pdf there (a quick google should turn it up though)
                – Pieter
                Jan 30 '09 at 15:22










              • Ok, thanks for good example and explanation. Here is my question though: why compiler cannot figure out where template is called, and compile those files first before compiling definition file? I can imagine it can be done in a simple case... Is the answer that interdependencies will mess up the order pretty fast?
                – Vlad
                Oct 11 '13 at 17:54








              1




              1




              "export" is standard, but it's just hard to implement so most of the compiler teams just haven't done yet.
              – vava
              Jan 30 '09 at 10:27




              "export" is standard, but it's just hard to implement so most of the compiler teams just haven't done yet.
              – vava
              Jan 30 '09 at 10:27




              5




              5




              export doesn't eliminate the need for source disclosure, nor does it reduce compile dependencies, while it requires a massive effort from compiler builders. So Herb Sutter himself asked compiler builders to 'forget about' export. As the time investment needed would be better spend elsewhere...
              – Pieter
              Jan 30 '09 at 15:13




              export doesn't eliminate the need for source disclosure, nor does it reduce compile dependencies, while it requires a massive effort from compiler builders. So Herb Sutter himself asked compiler builders to 'forget about' export. As the time investment needed would be better spend elsewhere...
              – Pieter
              Jan 30 '09 at 15:13




              2




              2




              So I don't think export isn't implemented 'yet'. It'll probably never get done by anyone else than EDG after the others saw how long it took, and how little was gained
              – Pieter
              Jan 30 '09 at 15:14




              So I don't think export isn't implemented 'yet'. It'll probably never get done by anyone else than EDG after the others saw how long it took, and how little was gained
              – Pieter
              Jan 30 '09 at 15:14




              3




              3




              If that interests you, the paper is called "Why we can't afford export", it's listed on his blog (gotw.ca/publications) but no pdf there (a quick google should turn it up though)
              – Pieter
              Jan 30 '09 at 15:22




              If that interests you, the paper is called "Why we can't afford export", it's listed on his blog (gotw.ca/publications) but no pdf there (a quick google should turn it up though)
              – Pieter
              Jan 30 '09 at 15:22












              Ok, thanks for good example and explanation. Here is my question though: why compiler cannot figure out where template is called, and compile those files first before compiling definition file? I can imagine it can be done in a simple case... Is the answer that interdependencies will mess up the order pretty fast?
              – Vlad
              Oct 11 '13 at 17:54




              Ok, thanks for good example and explanation. Here is my question though: why compiler cannot figure out where template is called, and compile those files first before compiling definition file? I can imagine it can be done in a simple case... Is the answer that interdependencies will mess up the order pretty fast?
              – Vlad
              Oct 11 '13 at 17:54










              up vote
              50
              down vote













              Actually, prior to C++11 the standard defined the export keyword that would make it possible to declare templates in a header file and implement them elsewhere.



              None of the popular compilers implemented this keyword. The only one I know about is the frontend written by the Edison Design Group, which is used by the Comeau C++ compiler. All others required you to write templates in header files, because the compiler needs the template definition for proper instantiation (as others pointed out already).



              As a result, the ISO C++ standard committee decided to remove the export feature of templates with C++11.






              share|improve this answer



















              • 38




                In a consequence export template was removed from C++11.
                – johannes
                Oct 23 '11 at 0:47






              • 5




                @johannes: I didn't catch that, thanks. Practically speaking, you couldn't use export anyway since that would tie you in with the Comeau compiler. It was a "dead feature"; just one I would have loved to see implemented ubiquitously.
                – DevSolar
                Oct 23 '11 at 6:06






              • 3




                ...and a couple of years later, I finally understood what export would actually have given us, and what not... and now I wholeheartedly agree with the EDG people: It would not have brought us what most people (myself in '11 included) think it would, and the C++ standard is better off without it.
                – DevSolar
                Nov 19 '15 at 10:27








              • 1




                @DevSolar : this paper is political, repetitive and badly written. that's not usual standard level prose there. Uneedingly long and boring, saying basically 3 times the same things accross tens of pages. But I am now informed that export is not export. That's a good intel !
                – v.oddou
                Apr 25 '16 at 9:51






              • 1




                @v.oddou: Good developer and good technical writer are two seperate skillsets. Some can do both, many can't. ;-)
                – DevSolar
                Apr 25 '16 at 9:58















              up vote
              50
              down vote













              Actually, prior to C++11 the standard defined the export keyword that would make it possible to declare templates in a header file and implement them elsewhere.



              None of the popular compilers implemented this keyword. The only one I know about is the frontend written by the Edison Design Group, which is used by the Comeau C++ compiler. All others required you to write templates in header files, because the compiler needs the template definition for proper instantiation (as others pointed out already).



              As a result, the ISO C++ standard committee decided to remove the export feature of templates with C++11.






              share|improve this answer



















              • 38




                In a consequence export template was removed from C++11.
                – johannes
                Oct 23 '11 at 0:47






              • 5




                @johannes: I didn't catch that, thanks. Practically speaking, you couldn't use export anyway since that would tie you in with the Comeau compiler. It was a "dead feature"; just one I would have loved to see implemented ubiquitously.
                – DevSolar
                Oct 23 '11 at 6:06






              • 3




                ...and a couple of years later, I finally understood what export would actually have given us, and what not... and now I wholeheartedly agree with the EDG people: It would not have brought us what most people (myself in '11 included) think it would, and the C++ standard is better off without it.
                – DevSolar
                Nov 19 '15 at 10:27








              • 1




                @DevSolar : this paper is political, repetitive and badly written. that's not usual standard level prose there. Uneedingly long and boring, saying basically 3 times the same things accross tens of pages. But I am now informed that export is not export. That's a good intel !
                – v.oddou
                Apr 25 '16 at 9:51






              • 1




                @v.oddou: Good developer and good technical writer are two seperate skillsets. Some can do both, many can't. ;-)
                – DevSolar
                Apr 25 '16 at 9:58













              up vote
              50
              down vote










              up vote
              50
              down vote









              Actually, prior to C++11 the standard defined the export keyword that would make it possible to declare templates in a header file and implement them elsewhere.



              None of the popular compilers implemented this keyword. The only one I know about is the frontend written by the Edison Design Group, which is used by the Comeau C++ compiler. All others required you to write templates in header files, because the compiler needs the template definition for proper instantiation (as others pointed out already).



              As a result, the ISO C++ standard committee decided to remove the export feature of templates with C++11.






              share|improve this answer














              Actually, prior to C++11 the standard defined the export keyword that would make it possible to declare templates in a header file and implement them elsewhere.



              None of the popular compilers implemented this keyword. The only one I know about is the frontend written by the Edison Design Group, which is used by the Comeau C++ compiler. All others required you to write templates in header files, because the compiler needs the template definition for proper instantiation (as others pointed out already).



              As a result, the ISO C++ standard committee decided to remove the export feature of templates with C++11.







              share|improve this answer














              share|improve this answer



              share|improve this answer








              edited Oct 19 at 11:58

























              answered Jan 30 '09 at 13:38









              DevSolar

              47.2k1294164




              47.2k1294164








              • 38




                In a consequence export template was removed from C++11.
                – johannes
                Oct 23 '11 at 0:47






              • 5




                @johannes: I didn't catch that, thanks. Practically speaking, you couldn't use export anyway since that would tie you in with the Comeau compiler. It was a "dead feature"; just one I would have loved to see implemented ubiquitously.
                – DevSolar
                Oct 23 '11 at 6:06






              • 3




                ...and a couple of years later, I finally understood what export would actually have given us, and what not... and now I wholeheartedly agree with the EDG people: It would not have brought us what most people (myself in '11 included) think it would, and the C++ standard is better off without it.
                – DevSolar
                Nov 19 '15 at 10:27








              • 1




                @DevSolar : this paper is political, repetitive and badly written. that's not usual standard level prose there. Uneedingly long and boring, saying basically 3 times the same things accross tens of pages. But I am now informed that export is not export. That's a good intel !
                – v.oddou
                Apr 25 '16 at 9:51






              • 1




                @v.oddou: Good developer and good technical writer are two seperate skillsets. Some can do both, many can't. ;-)
                – DevSolar
                Apr 25 '16 at 9:58














              • 38




                In a consequence export template was removed from C++11.
                – johannes
                Oct 23 '11 at 0:47






              • 5




                @johannes: I didn't catch that, thanks. Practically speaking, you couldn't use export anyway since that would tie you in with the Comeau compiler. It was a "dead feature"; just one I would have loved to see implemented ubiquitously.
                – DevSolar
                Oct 23 '11 at 6:06






              • 3




                ...and a couple of years later, I finally understood what export would actually have given us, and what not... and now I wholeheartedly agree with the EDG people: It would not have brought us what most people (myself in '11 included) think it would, and the C++ standard is better off without it.
                – DevSolar
                Nov 19 '15 at 10:27








              • 1




                @DevSolar : this paper is political, repetitive and badly written. that's not usual standard level prose there. Uneedingly long and boring, saying basically 3 times the same things accross tens of pages. But I am now informed that export is not export. That's a good intel !
                – v.oddou
                Apr 25 '16 at 9:51






              • 1




                @v.oddou: Good developer and good technical writer are two seperate skillsets. Some can do both, many can't. ;-)
                – DevSolar
                Apr 25 '16 at 9:58








              38




              38




              In a consequence export template was removed from C++11.
              – johannes
              Oct 23 '11 at 0:47




              In a consequence export template was removed from C++11.
              – johannes
              Oct 23 '11 at 0:47




              5




              5




              @johannes: I didn't catch that, thanks. Practically speaking, you couldn't use export anyway since that would tie you in with the Comeau compiler. It was a "dead feature"; just one I would have loved to see implemented ubiquitously.
              – DevSolar
              Oct 23 '11 at 6:06




              @johannes: I didn't catch that, thanks. Practically speaking, you couldn't use export anyway since that would tie you in with the Comeau compiler. It was a "dead feature"; just one I would have loved to see implemented ubiquitously.
              – DevSolar
              Oct 23 '11 at 6:06




              3




              3




              ...and a couple of years later, I finally understood what export would actually have given us, and what not... and now I wholeheartedly agree with the EDG people: It would not have brought us what most people (myself in '11 included) think it would, and the C++ standard is better off without it.
              – DevSolar
              Nov 19 '15 at 10:27






              ...and a couple of years later, I finally understood what export would actually have given us, and what not... and now I wholeheartedly agree with the EDG people: It would not have brought us what most people (myself in '11 included) think it would, and the C++ standard is better off without it.
              – DevSolar
              Nov 19 '15 at 10:27






              1




              1




              @DevSolar : this paper is political, repetitive and badly written. that's not usual standard level prose there. Uneedingly long and boring, saying basically 3 times the same things accross tens of pages. But I am now informed that export is not export. That's a good intel !
              – v.oddou
              Apr 25 '16 at 9:51




              @DevSolar : this paper is political, repetitive and badly written. that's not usual standard level prose there. Uneedingly long and boring, saying basically 3 times the same things accross tens of pages. But I am now informed that export is not export. That's a good intel !
              – v.oddou
              Apr 25 '16 at 9:51




              1




              1




              @v.oddou: Good developer and good technical writer are two seperate skillsets. Some can do both, many can't. ;-)
              – DevSolar
              Apr 25 '16 at 9:58




              @v.oddou: Good developer and good technical writer are two seperate skillsets. Some can do both, many can't. ;-)
              – DevSolar
              Apr 25 '16 at 9:58










              up vote
              32
              down vote













              Although standard C++ has no such requirement, some compilers require that all function and class templates need to be made available in every translation unit they are used. In effect, for those compilers, the bodies of template functions must be made available in a header file. To repeat: that means those compilers won't allow them to be defined in non-header files such as .cpp files



              There is an export keyword which is supposed to mitigate this problem, but it's nowhere close to being portable.






              share|improve this answer























              • Why can't I implement them in .cpp file with the keyword "inline"?
                – MainID
                Jan 30 '09 at 10:20






              • 2




                You can, and you don't have to put "inline" even. But you'd be able to use them just in that cpp file and nowhere else.
                – vava
                Jan 30 '09 at 10:28






              • 8




                This is almost the most accurate answer, except "that means those compilers won't allow them to be defined in non-header files such as .cpp files" is patently false.
                – Lightness Races in Orbit
                Aug 14 '11 at 17:59

















              up vote
              32
              down vote













              Although standard C++ has no such requirement, some compilers require that all function and class templates need to be made available in every translation unit they are used. In effect, for those compilers, the bodies of template functions must be made available in a header file. To repeat: that means those compilers won't allow them to be defined in non-header files such as .cpp files



              There is an export keyword which is supposed to mitigate this problem, but it's nowhere close to being portable.






              share|improve this answer























              • Why can't I implement them in .cpp file with the keyword "inline"?
                – MainID
                Jan 30 '09 at 10:20






              • 2




                You can, and you don't have to put "inline" even. But you'd be able to use them just in that cpp file and nowhere else.
                – vava
                Jan 30 '09 at 10:28






              • 8




                This is almost the most accurate answer, except "that means those compilers won't allow them to be defined in non-header files such as .cpp files" is patently false.
                – Lightness Races in Orbit
                Aug 14 '11 at 17:59















              up vote
              32
              down vote










              up vote
              32
              down vote









              Although standard C++ has no such requirement, some compilers require that all function and class templates need to be made available in every translation unit they are used. In effect, for those compilers, the bodies of template functions must be made available in a header file. To repeat: that means those compilers won't allow them to be defined in non-header files such as .cpp files



              There is an export keyword which is supposed to mitigate this problem, but it's nowhere close to being portable.






              share|improve this answer














              Although standard C++ has no such requirement, some compilers require that all function and class templates need to be made available in every translation unit they are used. In effect, for those compilers, the bodies of template functions must be made available in a header file. To repeat: that means those compilers won't allow them to be defined in non-header files such as .cpp files



              There is an export keyword which is supposed to mitigate this problem, but it's nowhere close to being portable.







              share|improve this answer














              share|improve this answer



              share|improve this answer








              edited Sep 19 '13 at 17:16









              Jonny Henly

              3,44041839




              3,44041839










              answered Jan 30 '09 at 10:15









              Anton Gogolev

              90.2k32170264




              90.2k32170264












              • Why can't I implement them in .cpp file with the keyword "inline"?
                – MainID
                Jan 30 '09 at 10:20






              • 2




                You can, and you don't have to put "inline" even. But you'd be able to use them just in that cpp file and nowhere else.
                – vava
                Jan 30 '09 at 10:28






              • 8




                This is almost the most accurate answer, except "that means those compilers won't allow them to be defined in non-header files such as .cpp files" is patently false.
                – Lightness Races in Orbit
                Aug 14 '11 at 17:59




















              • Why can't I implement them in .cpp file with the keyword "inline"?
                – MainID
                Jan 30 '09 at 10:20






              • 2




                You can, and you don't have to put "inline" even. But you'd be able to use them just in that cpp file and nowhere else.
                – vava
                Jan 30 '09 at 10:28






              • 8




                This is almost the most accurate answer, except "that means those compilers won't allow them to be defined in non-header files such as .cpp files" is patently false.
                – Lightness Races in Orbit
                Aug 14 '11 at 17:59


















              Why can't I implement them in .cpp file with the keyword "inline"?
              – MainID
              Jan 30 '09 at 10:20




              Why can't I implement them in .cpp file with the keyword "inline"?
              – MainID
              Jan 30 '09 at 10:20




              2




              2




              You can, and you don't have to put "inline" even. But you'd be able to use them just in that cpp file and nowhere else.
              – vava
              Jan 30 '09 at 10:28




              You can, and you don't have to put "inline" even. But you'd be able to use them just in that cpp file and nowhere else.
              – vava
              Jan 30 '09 at 10:28




              8




              8




              This is almost the most accurate answer, except "that means those compilers won't allow them to be defined in non-header files such as .cpp files" is patently false.
              – Lightness Races in Orbit
              Aug 14 '11 at 17:59






              This is almost the most accurate answer, except "that means those compilers won't allow them to be defined in non-header files such as .cpp files" is patently false.
              – Lightness Races in Orbit
              Aug 14 '11 at 17:59












              up vote
              26
              down vote













              Templates must be used in headers because the compiler needs to instantiate different versions of the code, depending on the parameters given/deduced for template parameters. Remember that a template doesn't represent code directly, but a template for several versions of that code.
              When you compile a non-template function in a .cpp file, you are compiling a concrete function/class. This is not the case for templates, which can be instantiated with different types, namely, concrete code must be emitted when replacing template parameters with concrete types.



              There was a feature with the export keyword that was meant to be used for separate compilation.
              The export feature is deprecated in C++11 and, AFAIK, only one compiler implemented it. You shouldn't make use of export. Separate compilation is not possible in C++ or C++11 but maybe in C++17, if concepts make it in, we could have some way of separate compilation.



              For separate compilation to be achieved, separate template body checking must be possible. It seems that a solution is possible with concepts. Take a look at this paper recently presented at the
              standards commitee meeting. I think this is not the only requirement, since you still need to instantiate code for the template code in user code.



              The separate compilation problem for templates I guess it's also a problem that is arising with the migration to modules, which is currently being worked.






              share|improve this answer



























                up vote
                26
                down vote













                Templates must be used in headers because the compiler needs to instantiate different versions of the code, depending on the parameters given/deduced for template parameters. Remember that a template doesn't represent code directly, but a template for several versions of that code.
                When you compile a non-template function in a .cpp file, you are compiling a concrete function/class. This is not the case for templates, which can be instantiated with different types, namely, concrete code must be emitted when replacing template parameters with concrete types.



                There was a feature with the export keyword that was meant to be used for separate compilation.
                The export feature is deprecated in C++11 and, AFAIK, only one compiler implemented it. You shouldn't make use of export. Separate compilation is not possible in C++ or C++11 but maybe in C++17, if concepts make it in, we could have some way of separate compilation.



                For separate compilation to be achieved, separate template body checking must be possible. It seems that a solution is possible with concepts. Take a look at this paper recently presented at the
                standards commitee meeting. I think this is not the only requirement, since you still need to instantiate code for the template code in user code.



                The separate compilation problem for templates I guess it's also a problem that is arising with the migration to modules, which is currently being worked.






                share|improve this answer

























                  up vote
                  26
                  down vote










                  up vote
                  26
                  down vote









                  Templates must be used in headers because the compiler needs to instantiate different versions of the code, depending on the parameters given/deduced for template parameters. Remember that a template doesn't represent code directly, but a template for several versions of that code.
                  When you compile a non-template function in a .cpp file, you are compiling a concrete function/class. This is not the case for templates, which can be instantiated with different types, namely, concrete code must be emitted when replacing template parameters with concrete types.



                  There was a feature with the export keyword that was meant to be used for separate compilation.
                  The export feature is deprecated in C++11 and, AFAIK, only one compiler implemented it. You shouldn't make use of export. Separate compilation is not possible in C++ or C++11 but maybe in C++17, if concepts make it in, we could have some way of separate compilation.



                  For separate compilation to be achieved, separate template body checking must be possible. It seems that a solution is possible with concepts. Take a look at this paper recently presented at the
                  standards commitee meeting. I think this is not the only requirement, since you still need to instantiate code for the template code in user code.



                  The separate compilation problem for templates I guess it's also a problem that is arising with the migration to modules, which is currently being worked.






                  share|improve this answer














                  Templates must be used in headers because the compiler needs to instantiate different versions of the code, depending on the parameters given/deduced for template parameters. Remember that a template doesn't represent code directly, but a template for several versions of that code.
                  When you compile a non-template function in a .cpp file, you are compiling a concrete function/class. This is not the case for templates, which can be instantiated with different types, namely, concrete code must be emitted when replacing template parameters with concrete types.



                  There was a feature with the export keyword that was meant to be used for separate compilation.
                  The export feature is deprecated in C++11 and, AFAIK, only one compiler implemented it. You shouldn't make use of export. Separate compilation is not possible in C++ or C++11 but maybe in C++17, if concepts make it in, we could have some way of separate compilation.



                  For separate compilation to be achieved, separate template body checking must be possible. It seems that a solution is possible with concepts. Take a look at this paper recently presented at the
                  standards commitee meeting. I think this is not the only requirement, since you still need to instantiate code for the template code in user code.



                  The separate compilation problem for templates I guess it's also a problem that is arising with the migration to modules, which is currently being worked.







                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited May 12 '13 at 16:48

























                  answered May 12 '13 at 16:42









                  Germán Diago

                  4,97312744




                  4,97312744






















                      up vote
                      13
                      down vote













                      It means that the most portable way to define method implementations of template classes is to define them inside the template class definition.



                      template < typename ... >
                      class MyClass
                      {

                      int myMethod()
                      {
                      // Not just declaration. Add method implementation here
                      }
                      };





                      share|improve this answer



























                        up vote
                        13
                        down vote













                        It means that the most portable way to define method implementations of template classes is to define them inside the template class definition.



                        template < typename ... >
                        class MyClass
                        {

                        int myMethod()
                        {
                        // Not just declaration. Add method implementation here
                        }
                        };





                        share|improve this answer

























                          up vote
                          13
                          down vote










                          up vote
                          13
                          down vote









                          It means that the most portable way to define method implementations of template classes is to define them inside the template class definition.



                          template < typename ... >
                          class MyClass
                          {

                          int myMethod()
                          {
                          // Not just declaration. Add method implementation here
                          }
                          };





                          share|improve this answer














                          It means that the most portable way to define method implementations of template classes is to define them inside the template class definition.



                          template < typename ... >
                          class MyClass
                          {

                          int myMethod()
                          {
                          // Not just declaration. Add method implementation here
                          }
                          };






                          share|improve this answer














                          share|improve this answer



                          share|improve this answer








                          edited Feb 10 '09 at 21:44









                          Evan Teran

                          65.9k18155218




                          65.9k18155218










                          answered Jan 30 '09 at 10:53









                          Benoît

                          14.6k53663




                          14.6k53663






















                              up vote
                              9
                              down vote













                              Even though there are plenty of good explanations above, I'm missing a practical way to separate templates into header and body.

                              My main concern is avoiding recompilation of all template users, when I change its definition.

                              Having all template instantiations in the template body is not a viable solution for me, since the template author may not know all if its usage and the template user may not have the right to modify it.

                              I took the following approach, which works also for older compilers (gcc 4.3.4, aCC A.03.13).



                              For each template usage there's a typedef in its own header file (generated from the UML model). Its body contains the instantiation (which ends up in a library which is linked in at the end).

                              Each user of the template includes that header file and uses the typedef.



                              A schematic example:



                              MyTemplate.h:



                              #ifndef MyTemplate_h
                              #define MyTemplate_h 1

                              template <class T>
                              class MyTemplate
                              {
                              public:
                              MyTemplate(const T& rt);
                              void dump();
                              T t;
                              };

                              #endif


                              MyTemplate.cpp:



                              #include "MyTemplate.h"
                              #include <iostream>

                              template <class T>
                              MyTemplate<T>::MyTemplate(const T& rt)
                              : t(rt)
                              {
                              }

                              template <class T>
                              void MyTemplate<T>::dump()
                              {
                              cerr << t << endl;
                              }


                              MyInstantiatedTemplate.h:



                              #ifndef MyInstantiatedTemplate_h
                              #define MyInstantiatedTemplate_h 1
                              #include "MyTemplate.h"

                              typedef MyTemplate< int > MyInstantiatedTemplate;

                              #endif


                              MyInstantiatedTemplate.cpp:



                              #include "MyTemplate.cpp"

                              template class MyTemplate< int >;


                              main.cpp:



                              #include "MyInstantiatedTemplate.h"

                              int main()
                              {
                              MyInstantiatedTemplate m(100);
                              m.dump();
                              return 0;
                              }


                              This way only the template instantiations will need to be recompiled, not all template users (and dependencies).






                              share|improve this answer



























                                up vote
                                9
                                down vote













                                Even though there are plenty of good explanations above, I'm missing a practical way to separate templates into header and body.

                                My main concern is avoiding recompilation of all template users, when I change its definition.

                                Having all template instantiations in the template body is not a viable solution for me, since the template author may not know all if its usage and the template user may not have the right to modify it.

                                I took the following approach, which works also for older compilers (gcc 4.3.4, aCC A.03.13).



                                For each template usage there's a typedef in its own header file (generated from the UML model). Its body contains the instantiation (which ends up in a library which is linked in at the end).

                                Each user of the template includes that header file and uses the typedef.



                                A schematic example:



                                MyTemplate.h:



                                #ifndef MyTemplate_h
                                #define MyTemplate_h 1

                                template <class T>
                                class MyTemplate
                                {
                                public:
                                MyTemplate(const T& rt);
                                void dump();
                                T t;
                                };

                                #endif


                                MyTemplate.cpp:



                                #include "MyTemplate.h"
                                #include <iostream>

                                template <class T>
                                MyTemplate<T>::MyTemplate(const T& rt)
                                : t(rt)
                                {
                                }

                                template <class T>
                                void MyTemplate<T>::dump()
                                {
                                cerr << t << endl;
                                }


                                MyInstantiatedTemplate.h:



                                #ifndef MyInstantiatedTemplate_h
                                #define MyInstantiatedTemplate_h 1
                                #include "MyTemplate.h"

                                typedef MyTemplate< int > MyInstantiatedTemplate;

                                #endif


                                MyInstantiatedTemplate.cpp:



                                #include "MyTemplate.cpp"

                                template class MyTemplate< int >;


                                main.cpp:



                                #include "MyInstantiatedTemplate.h"

                                int main()
                                {
                                MyInstantiatedTemplate m(100);
                                m.dump();
                                return 0;
                                }


                                This way only the template instantiations will need to be recompiled, not all template users (and dependencies).






                                share|improve this answer

























                                  up vote
                                  9
                                  down vote










                                  up vote
                                  9
                                  down vote









                                  Even though there are plenty of good explanations above, I'm missing a practical way to separate templates into header and body.

                                  My main concern is avoiding recompilation of all template users, when I change its definition.

                                  Having all template instantiations in the template body is not a viable solution for me, since the template author may not know all if its usage and the template user may not have the right to modify it.

                                  I took the following approach, which works also for older compilers (gcc 4.3.4, aCC A.03.13).



                                  For each template usage there's a typedef in its own header file (generated from the UML model). Its body contains the instantiation (which ends up in a library which is linked in at the end).

                                  Each user of the template includes that header file and uses the typedef.



                                  A schematic example:



                                  MyTemplate.h:



                                  #ifndef MyTemplate_h
                                  #define MyTemplate_h 1

                                  template <class T>
                                  class MyTemplate
                                  {
                                  public:
                                  MyTemplate(const T& rt);
                                  void dump();
                                  T t;
                                  };

                                  #endif


                                  MyTemplate.cpp:



                                  #include "MyTemplate.h"
                                  #include <iostream>

                                  template <class T>
                                  MyTemplate<T>::MyTemplate(const T& rt)
                                  : t(rt)
                                  {
                                  }

                                  template <class T>
                                  void MyTemplate<T>::dump()
                                  {
                                  cerr << t << endl;
                                  }


                                  MyInstantiatedTemplate.h:



                                  #ifndef MyInstantiatedTemplate_h
                                  #define MyInstantiatedTemplate_h 1
                                  #include "MyTemplate.h"

                                  typedef MyTemplate< int > MyInstantiatedTemplate;

                                  #endif


                                  MyInstantiatedTemplate.cpp:



                                  #include "MyTemplate.cpp"

                                  template class MyTemplate< int >;


                                  main.cpp:



                                  #include "MyInstantiatedTemplate.h"

                                  int main()
                                  {
                                  MyInstantiatedTemplate m(100);
                                  m.dump();
                                  return 0;
                                  }


                                  This way only the template instantiations will need to be recompiled, not all template users (and dependencies).






                                  share|improve this answer














                                  Even though there are plenty of good explanations above, I'm missing a practical way to separate templates into header and body.

                                  My main concern is avoiding recompilation of all template users, when I change its definition.

                                  Having all template instantiations in the template body is not a viable solution for me, since the template author may not know all if its usage and the template user may not have the right to modify it.

                                  I took the following approach, which works also for older compilers (gcc 4.3.4, aCC A.03.13).



                                  For each template usage there's a typedef in its own header file (generated from the UML model). Its body contains the instantiation (which ends up in a library which is linked in at the end).

                                  Each user of the template includes that header file and uses the typedef.



                                  A schematic example:



                                  MyTemplate.h:



                                  #ifndef MyTemplate_h
                                  #define MyTemplate_h 1

                                  template <class T>
                                  class MyTemplate
                                  {
                                  public:
                                  MyTemplate(const T& rt);
                                  void dump();
                                  T t;
                                  };

                                  #endif


                                  MyTemplate.cpp:



                                  #include "MyTemplate.h"
                                  #include <iostream>

                                  template <class T>
                                  MyTemplate<T>::MyTemplate(const T& rt)
                                  : t(rt)
                                  {
                                  }

                                  template <class T>
                                  void MyTemplate<T>::dump()
                                  {
                                  cerr << t << endl;
                                  }


                                  MyInstantiatedTemplate.h:



                                  #ifndef MyInstantiatedTemplate_h
                                  #define MyInstantiatedTemplate_h 1
                                  #include "MyTemplate.h"

                                  typedef MyTemplate< int > MyInstantiatedTemplate;

                                  #endif


                                  MyInstantiatedTemplate.cpp:



                                  #include "MyTemplate.cpp"

                                  template class MyTemplate< int >;


                                  main.cpp:



                                  #include "MyInstantiatedTemplate.h"

                                  int main()
                                  {
                                  MyInstantiatedTemplate m(100);
                                  m.dump();
                                  return 0;
                                  }


                                  This way only the template instantiations will need to be recompiled, not all template users (and dependencies).







                                  share|improve this answer














                                  share|improve this answer



                                  share|improve this answer








                                  edited May 12 '16 at 14:08

























                                  answered May 12 '16 at 14:02









                                  lafrecciablu

                                  14016




                                  14016






















                                      up vote
                                      6
                                      down vote













                                      That is exactly correct because the compiler has to know what type it is for allocation. So template classes, functions, enums,etc.. must be implemented as well in the header file if it is to be made public or part of a library (static or dynamic) because header files are NOT compiled unlike the c/cpp files which are. If the compiler doesn't know the type is can't compile it. In .Net it can because all objects derive from the Object class. This is not .Net.






                                      share|improve this answer



















                                      • 5




                                        "header files are NOT compiled" - that's a really odd way of describing it. Header files can be part of a translation unit, just like a "c/cpp" file.
                                        – Flexo
                                        Sep 17 '11 at 12:26






                                      • 1




                                        In fact, it's almost the opposite of the truth, which is that header files are very frequently compiled many times, whereas a source file is usually compiled once.
                                        – xaxxon
                                        Dec 21 '15 at 22:46















                                      up vote
                                      6
                                      down vote













                                      That is exactly correct because the compiler has to know what type it is for allocation. So template classes, functions, enums,etc.. must be implemented as well in the header file if it is to be made public or part of a library (static or dynamic) because header files are NOT compiled unlike the c/cpp files which are. If the compiler doesn't know the type is can't compile it. In .Net it can because all objects derive from the Object class. This is not .Net.






                                      share|improve this answer



















                                      • 5




                                        "header files are NOT compiled" - that's a really odd way of describing it. Header files can be part of a translation unit, just like a "c/cpp" file.
                                        – Flexo
                                        Sep 17 '11 at 12:26






                                      • 1




                                        In fact, it's almost the opposite of the truth, which is that header files are very frequently compiled many times, whereas a source file is usually compiled once.
                                        – xaxxon
                                        Dec 21 '15 at 22:46













                                      up vote
                                      6
                                      down vote










                                      up vote
                                      6
                                      down vote









                                      That is exactly correct because the compiler has to know what type it is for allocation. So template classes, functions, enums,etc.. must be implemented as well in the header file if it is to be made public or part of a library (static or dynamic) because header files are NOT compiled unlike the c/cpp files which are. If the compiler doesn't know the type is can't compile it. In .Net it can because all objects derive from the Object class. This is not .Net.






                                      share|improve this answer














                                      That is exactly correct because the compiler has to know what type it is for allocation. So template classes, functions, enums,etc.. must be implemented as well in the header file if it is to be made public or part of a library (static or dynamic) because header files are NOT compiled unlike the c/cpp files which are. If the compiler doesn't know the type is can't compile it. In .Net it can because all objects derive from the Object class. This is not .Net.







                                      share|improve this answer














                                      share|improve this answer



                                      share|improve this answer








                                      edited Sep 17 '11 at 12:27









                                      Flexo

                                      68.2k21140224




                                      68.2k21140224










                                      answered Sep 17 '11 at 3:40









                                      Robert

                                      7911




                                      7911








                                      • 5




                                        "header files are NOT compiled" - that's a really odd way of describing it. Header files can be part of a translation unit, just like a "c/cpp" file.
                                        – Flexo
                                        Sep 17 '11 at 12:26






                                      • 1




                                        In fact, it's almost the opposite of the truth, which is that header files are very frequently compiled many times, whereas a source file is usually compiled once.
                                        – xaxxon
                                        Dec 21 '15 at 22:46














                                      • 5




                                        "header files are NOT compiled" - that's a really odd way of describing it. Header files can be part of a translation unit, just like a "c/cpp" file.
                                        – Flexo
                                        Sep 17 '11 at 12:26






                                      • 1




                                        In fact, it's almost the opposite of the truth, which is that header files are very frequently compiled many times, whereas a source file is usually compiled once.
                                        – xaxxon
                                        Dec 21 '15 at 22:46








                                      5




                                      5




                                      "header files are NOT compiled" - that's a really odd way of describing it. Header files can be part of a translation unit, just like a "c/cpp" file.
                                      – Flexo
                                      Sep 17 '11 at 12:26




                                      "header files are NOT compiled" - that's a really odd way of describing it. Header files can be part of a translation unit, just like a "c/cpp" file.
                                      – Flexo
                                      Sep 17 '11 at 12:26




                                      1




                                      1




                                      In fact, it's almost the opposite of the truth, which is that header files are very frequently compiled many times, whereas a source file is usually compiled once.
                                      – xaxxon
                                      Dec 21 '15 at 22:46




                                      In fact, it's almost the opposite of the truth, which is that header files are very frequently compiled many times, whereas a source file is usually compiled once.
                                      – xaxxon
                                      Dec 21 '15 at 22:46










                                      up vote
                                      6
                                      down vote













                                      If the concern is the extra compilation time and binary size bloat produced by compiling the .h as part of all the .cpp modules using it, in many cases what you can do is make the template class descend from a non-templatized base class for non type-dependent parts of the interface, and that base class can have its implementation in the .cpp file.






                                      share|improve this answer

















                                      • 1




                                        This response should be modded up quite more. I "independently" discovered your same approach and was specifically looking for somebody else to have used it already, since I'm curious if it's an official pattern and whether it's got a name. My approach is to implement a class XBase wherever I need to implement a template class X, putting the type-dependent parts in X and all the rest in XBase.
                                        – Fabio A.
                                        Nov 4 '16 at 8:38

















                                      up vote
                                      6
                                      down vote













                                      If the concern is the extra compilation time and binary size bloat produced by compiling the .h as part of all the .cpp modules using it, in many cases what you can do is make the template class descend from a non-templatized base class for non type-dependent parts of the interface, and that base class can have its implementation in the .cpp file.






                                      share|improve this answer

















                                      • 1




                                        This response should be modded up quite more. I "independently" discovered your same approach and was specifically looking for somebody else to have used it already, since I'm curious if it's an official pattern and whether it's got a name. My approach is to implement a class XBase wherever I need to implement a template class X, putting the type-dependent parts in X and all the rest in XBase.
                                        – Fabio A.
                                        Nov 4 '16 at 8:38















                                      up vote
                                      6
                                      down vote










                                      up vote
                                      6
                                      down vote









                                      If the concern is the extra compilation time and binary size bloat produced by compiling the .h as part of all the .cpp modules using it, in many cases what you can do is make the template class descend from a non-templatized base class for non type-dependent parts of the interface, and that base class can have its implementation in the .cpp file.






                                      share|improve this answer












                                      If the concern is the extra compilation time and binary size bloat produced by compiling the .h as part of all the .cpp modules using it, in many cases what you can do is make the template class descend from a non-templatized base class for non type-dependent parts of the interface, and that base class can have its implementation in the .cpp file.







                                      share|improve this answer












                                      share|improve this answer



                                      share|improve this answer










                                      answered Jul 27 '16 at 5:01









                                      Eric Shaw

                                      9114




                                      9114








                                      • 1




                                        This response should be modded up quite more. I "independently" discovered your same approach and was specifically looking for somebody else to have used it already, since I'm curious if it's an official pattern and whether it's got a name. My approach is to implement a class XBase wherever I need to implement a template class X, putting the type-dependent parts in X and all the rest in XBase.
                                        – Fabio A.
                                        Nov 4 '16 at 8:38
















                                      • 1




                                        This response should be modded up quite more. I "independently" discovered your same approach and was specifically looking for somebody else to have used it already, since I'm curious if it's an official pattern and whether it's got a name. My approach is to implement a class XBase wherever I need to implement a template class X, putting the type-dependent parts in X and all the rest in XBase.
                                        – Fabio A.
                                        Nov 4 '16 at 8:38










                                      1




                                      1




                                      This response should be modded up quite more. I "independently" discovered your same approach and was specifically looking for somebody else to have used it already, since I'm curious if it's an official pattern and whether it's got a name. My approach is to implement a class XBase wherever I need to implement a template class X, putting the type-dependent parts in X and all the rest in XBase.
                                      – Fabio A.
                                      Nov 4 '16 at 8:38






                                      This response should be modded up quite more. I "independently" discovered your same approach and was specifically looking for somebody else to have used it already, since I'm curious if it's an official pattern and whether it's got a name. My approach is to implement a class XBase wherever I need to implement a template class X, putting the type-dependent parts in X and all the rest in XBase.
                                      – Fabio A.
                                      Nov 4 '16 at 8:38












                                      up vote
                                      2
                                      down vote













                                      A way to have separate implementation is as follows.



                                      //inner_foo.h

                                      template <typename T>
                                      struct Foo
                                      {
                                      void doSomething(T param);
                                      };


                                      //foo.tpp
                                      #include "inner_foo.h"
                                      template <typename T>
                                      void Foo<T>::doSomething(T param)
                                      {
                                      //implementation
                                      }


                                      //foo.h
                                      #include <foo.tpp>

                                      //main.cpp
                                      #include <foo.h>


                                      inner_foo has the forward declarations. foo.tpp has the implementation and include inner_foo.h; and foo.h will have just one line, to include foo.tpp.



                                      On compile time, contents of foo.h are copied to foo.tpp and then the whole file is copied to foo.h after which it compiles. This way, there is no limitations, and the naming is consistent, in exchange for one extra file.



                                      I do this because static analyzers for the code break when it does not see the forward declarations of class in *.tpp. This is annoying when writing code in any IDE or using YouCompleteMe or others.






                                      share|improve this answer

























                                        up vote
                                        2
                                        down vote













                                        A way to have separate implementation is as follows.



                                        //inner_foo.h

                                        template <typename T>
                                        struct Foo
                                        {
                                        void doSomething(T param);
                                        };


                                        //foo.tpp
                                        #include "inner_foo.h"
                                        template <typename T>
                                        void Foo<T>::doSomething(T param)
                                        {
                                        //implementation
                                        }


                                        //foo.h
                                        #include <foo.tpp>

                                        //main.cpp
                                        #include <foo.h>


                                        inner_foo has the forward declarations. foo.tpp has the implementation and include inner_foo.h; and foo.h will have just one line, to include foo.tpp.



                                        On compile time, contents of foo.h are copied to foo.tpp and then the whole file is copied to foo.h after which it compiles. This way, there is no limitations, and the naming is consistent, in exchange for one extra file.



                                        I do this because static analyzers for the code break when it does not see the forward declarations of class in *.tpp. This is annoying when writing code in any IDE or using YouCompleteMe or others.






                                        share|improve this answer























                                          up vote
                                          2
                                          down vote










                                          up vote
                                          2
                                          down vote









                                          A way to have separate implementation is as follows.



                                          //inner_foo.h

                                          template <typename T>
                                          struct Foo
                                          {
                                          void doSomething(T param);
                                          };


                                          //foo.tpp
                                          #include "inner_foo.h"
                                          template <typename T>
                                          void Foo<T>::doSomething(T param)
                                          {
                                          //implementation
                                          }


                                          //foo.h
                                          #include <foo.tpp>

                                          //main.cpp
                                          #include <foo.h>


                                          inner_foo has the forward declarations. foo.tpp has the implementation and include inner_foo.h; and foo.h will have just one line, to include foo.tpp.



                                          On compile time, contents of foo.h are copied to foo.tpp and then the whole file is copied to foo.h after which it compiles. This way, there is no limitations, and the naming is consistent, in exchange for one extra file.



                                          I do this because static analyzers for the code break when it does not see the forward declarations of class in *.tpp. This is annoying when writing code in any IDE or using YouCompleteMe or others.






                                          share|improve this answer












                                          A way to have separate implementation is as follows.



                                          //inner_foo.h

                                          template <typename T>
                                          struct Foo
                                          {
                                          void doSomething(T param);
                                          };


                                          //foo.tpp
                                          #include "inner_foo.h"
                                          template <typename T>
                                          void Foo<T>::doSomething(T param)
                                          {
                                          //implementation
                                          }


                                          //foo.h
                                          #include <foo.tpp>

                                          //main.cpp
                                          #include <foo.h>


                                          inner_foo has the forward declarations. foo.tpp has the implementation and include inner_foo.h; and foo.h will have just one line, to include foo.tpp.



                                          On compile time, contents of foo.h are copied to foo.tpp and then the whole file is copied to foo.h after which it compiles. This way, there is no limitations, and the naming is consistent, in exchange for one extra file.



                                          I do this because static analyzers for the code break when it does not see the forward declarations of class in *.tpp. This is annoying when writing code in any IDE or using YouCompleteMe or others.







                                          share|improve this answer












                                          share|improve this answer



                                          share|improve this answer










                                          answered May 13 '17 at 1:42









                                          Pranay

                                          224311




                                          224311






















                                              up vote
                                              1
                                              down vote













                                              The compiler will generate code for each template instantiation when you use a template during the compilation step.
                                              In the compilation and linking process .cpp files are converted to pure object or machine code which in them contains references or undefined symbols because the .h files that are included in your main.cpp have no implementation YET. These are ready to be linked with another object file that defines an implementation for your template and thus you have a full a.out executable.
                                              However since templates need to be processed in the compilation step in order to generate code for each template instantiation that you do in your main program, linking won't help because compiling the main.cpp into main.o and then compiling your template .cpp into template.o and then linking won't achieve the templates purpose because I'm linking different template instantiation to the same template implementation! And templates are supposed to do the opposite i.e to have ONE implementation but allow many available instantiations via the use of one class.



                                              Meaning typename T get's replaced during the compilation step not the linking step so if I try to compile a template without T being replaced as a concrete value type so it won't work because that's the definition of templates it's a compile time process, and btw meta-programming is all about using this definition.






                                              share|improve this answer



























                                                up vote
                                                1
                                                down vote













                                                The compiler will generate code for each template instantiation when you use a template during the compilation step.
                                                In the compilation and linking process .cpp files are converted to pure object or machine code which in them contains references or undefined symbols because the .h files that are included in your main.cpp have no implementation YET. These are ready to be linked with another object file that defines an implementation for your template and thus you have a full a.out executable.
                                                However since templates need to be processed in the compilation step in order to generate code for each template instantiation that you do in your main program, linking won't help because compiling the main.cpp into main.o and then compiling your template .cpp into template.o and then linking won't achieve the templates purpose because I'm linking different template instantiation to the same template implementation! And templates are supposed to do the opposite i.e to have ONE implementation but allow many available instantiations via the use of one class.



                                                Meaning typename T get's replaced during the compilation step not the linking step so if I try to compile a template without T being replaced as a concrete value type so it won't work because that's the definition of templates it's a compile time process, and btw meta-programming is all about using this definition.






                                                share|improve this answer

























                                                  up vote
                                                  1
                                                  down vote










                                                  up vote
                                                  1
                                                  down vote









                                                  The compiler will generate code for each template instantiation when you use a template during the compilation step.
                                                  In the compilation and linking process .cpp files are converted to pure object or machine code which in them contains references or undefined symbols because the .h files that are included in your main.cpp have no implementation YET. These are ready to be linked with another object file that defines an implementation for your template and thus you have a full a.out executable.
                                                  However since templates need to be processed in the compilation step in order to generate code for each template instantiation that you do in your main program, linking won't help because compiling the main.cpp into main.o and then compiling your template .cpp into template.o and then linking won't achieve the templates purpose because I'm linking different template instantiation to the same template implementation! And templates are supposed to do the opposite i.e to have ONE implementation but allow many available instantiations via the use of one class.



                                                  Meaning typename T get's replaced during the compilation step not the linking step so if I try to compile a template without T being replaced as a concrete value type so it won't work because that's the definition of templates it's a compile time process, and btw meta-programming is all about using this definition.






                                                  share|improve this answer














                                                  The compiler will generate code for each template instantiation when you use a template during the compilation step.
                                                  In the compilation and linking process .cpp files are converted to pure object or machine code which in them contains references or undefined symbols because the .h files that are included in your main.cpp have no implementation YET. These are ready to be linked with another object file that defines an implementation for your template and thus you have a full a.out executable.
                                                  However since templates need to be processed in the compilation step in order to generate code for each template instantiation that you do in your main program, linking won't help because compiling the main.cpp into main.o and then compiling your template .cpp into template.o and then linking won't achieve the templates purpose because I'm linking different template instantiation to the same template implementation! And templates are supposed to do the opposite i.e to have ONE implementation but allow many available instantiations via the use of one class.



                                                  Meaning typename T get's replaced during the compilation step not the linking step so if I try to compile a template without T being replaced as a concrete value type so it won't work because that's the definition of templates it's a compile time process, and btw meta-programming is all about using this definition.







                                                  share|improve this answer














                                                  share|improve this answer



                                                  share|improve this answer








                                                  edited Mar 16 '17 at 2:16

























                                                  answered Jul 19 '16 at 1:10









                                                  Moshe Rabaev

                                                  521417




                                                  521417






















                                                      up vote
                                                      1
                                                      down vote













                                                      Just to add something noteworthy here. One can define methods of a templated class just fine in the implementation file when they are not function templates.





                                                      myQueue.hpp:



                                                      template <class T> 
                                                      class QueueA {
                                                      int size;
                                                      ...
                                                      public:
                                                      template <class T> T dequeue() {
                                                      // implementation here
                                                      }

                                                      bool isEmpty();

                                                      ...
                                                      }




                                                      myQueue.cpp:



                                                      // implementation of regular methods goes like this:
                                                      template <class T> bool QueueA<T>::isEmpty() {
                                                      return this->size == 0;
                                                      }


                                                      main()
                                                      {
                                                      QueueA<char> Q;

                                                      ...
                                                      }





                                                      share|improve this answer

























                                                        up vote
                                                        1
                                                        down vote













                                                        Just to add something noteworthy here. One can define methods of a templated class just fine in the implementation file when they are not function templates.





                                                        myQueue.hpp:



                                                        template <class T> 
                                                        class QueueA {
                                                        int size;
                                                        ...
                                                        public:
                                                        template <class T> T dequeue() {
                                                        // implementation here
                                                        }

                                                        bool isEmpty();

                                                        ...
                                                        }




                                                        myQueue.cpp:



                                                        // implementation of regular methods goes like this:
                                                        template <class T> bool QueueA<T>::isEmpty() {
                                                        return this->size == 0;
                                                        }


                                                        main()
                                                        {
                                                        QueueA<char> Q;

                                                        ...
                                                        }





                                                        share|improve this answer























                                                          up vote
                                                          1
                                                          down vote










                                                          up vote
                                                          1
                                                          down vote









                                                          Just to add something noteworthy here. One can define methods of a templated class just fine in the implementation file when they are not function templates.





                                                          myQueue.hpp:



                                                          template <class T> 
                                                          class QueueA {
                                                          int size;
                                                          ...
                                                          public:
                                                          template <class T> T dequeue() {
                                                          // implementation here
                                                          }

                                                          bool isEmpty();

                                                          ...
                                                          }




                                                          myQueue.cpp:



                                                          // implementation of regular methods goes like this:
                                                          template <class T> bool QueueA<T>::isEmpty() {
                                                          return this->size == 0;
                                                          }


                                                          main()
                                                          {
                                                          QueueA<char> Q;

                                                          ...
                                                          }





                                                          share|improve this answer












                                                          Just to add something noteworthy here. One can define methods of a templated class just fine in the implementation file when they are not function templates.





                                                          myQueue.hpp:



                                                          template <class T> 
                                                          class QueueA {
                                                          int size;
                                                          ...
                                                          public:
                                                          template <class T> T dequeue() {
                                                          // implementation here
                                                          }

                                                          bool isEmpty();

                                                          ...
                                                          }




                                                          myQueue.cpp:



                                                          // implementation of regular methods goes like this:
                                                          template <class T> bool QueueA<T>::isEmpty() {
                                                          return this->size == 0;
                                                          }


                                                          main()
                                                          {
                                                          QueueA<char> Q;

                                                          ...
                                                          }






                                                          share|improve this answer












                                                          share|improve this answer



                                                          share|improve this answer










                                                          answered Jul 19 at 0:49









                                                          Nik-Lz

                                                          1,19031529




                                                          1,19031529

















                                                              protected by Marco A. Oct 15 '14 at 23:24



                                                              Thank you for your interest in this question.
                                                              Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).



                                                              Would you like to answer one of these unanswered questions instead?



                                                              Popular posts from this blog

                                                              Florida Star v. B. J. F.

                                                              Danny Elfman

                                                              Lugert, Oklahoma