Linker error when using extern template

I have a working code with a template. Like stl :: string, I mainly use my template with one parameter for several compilation units. To save time, I am trying to use extern instantiation . However, changing the lines as follows gives an error. What is the right way to do this? (PS Compiling on gcc with the C ++ 0x flag)

typedef myTemplate_base<commonType> myTemplate;
extern template class myTemplate_base<commonType>; //using "extern template myTemplate" wont work

I added an additional cpp file with the following project.

template class myTemplate_base<commonType>;

An error message appears in the linker (providing the line of the first instance of the object ( myTemplate someVar;) in the main file as an error source):

undefined link 'myTemplate_base :: ~ myTemplate_base ()'

However, this type is in a class with the following definition ~myTemplate() = default;

Edit: If you have a better headline, comment on the comment, so the right people will take a look at this.

Edit2: . In a funny case, adding template class myTemplate_base<commonType>significantly increases the size of the executable file (+ 100k in the binary 450 thousand), although the template is used mainly (for compilation I have to comment on the part extern). This indicates that the linker supports two template implementations with the same instance / me, something is missing.

+5
source share
1 answer

. g++ (Ubuntu/Linaro 4.6.1-9ubuntu3) 4.6.1. , . , (= default).

extern. extern , . , . , = default , , .

extern. , . , . , extern template, ( , ).


g++ -c -std=c++0x main.cpp
g++ -c -std=c++0x extern.cpp
g++ main.o extern.o

header.hpp

#pragma once

#include <iostream>
#include <string>
#include <typeinfo>

template< typename T >
class Foo
{
public:
   Foo( void ) :
      m_name( typeid(T).name() ),
      m_t( T() )
   { }

   // add or remove this to cause the error
   ~Foo( void ) = default;

   void printer( void )
   {
      std::cout << m_name << std::endl;
   }

   T returner( void )
   {
      return m_t;;
   }

private:
   std::string m_name;
   T m_t;
};

extern template class Foo<int>;

extern.cpp

#include "header.hpp"

template class Foo<int>;

main.cpp

#include "header.hpp"

int main()
{
   Foo<int> fi;
   fi.printer();

   Foo<float> ff;
   ff.printer();
}
+5

All Articles