samedi 3 janvier 2015

Can I put `extern template` into a header file?

Is putting an extern template in a header file and then do the explicit template instantiation in a unit compilation file valid ?


For example in the compiling example for g++, is this working to avoid the instancation of nothing<int> twice ? Why doesn't anybody write it like this and prefer to copy pase the extern template line in each .cpp file ?


A.hpp:



#ifndef HEADERC_A
#define HEADERC_A

template< typename T > struct nothing {};
extern template struct nothing<int>;

#endif


A.cpp:



#include "A.hpp"

template struct nothing<int>;


main.cpp:



#include "A.hpp"
#include <iostream>

int main()
{
nothing<int> n;
return 0;
}

Aucun commentaire:

Enregistrer un commentaire