Template in .cpp file
- Compiler uses template classes to create types by substituting template parameters, and this process is called instantiation.
- The type that is created from a template class is called a specialization.
//---------------------------------------------------------------
// in main.cpp
#include "temp.h"
int main()
{
Foo A;
Foo B = A;
return 0;
}
class Foo
{
public:
Foo() ;
~Foo() ;
Foo( Foo &rhs )
{
int test = 0 ;
};
};
#include "temp.cpp"
template < typename T>
Foo::Foo()
{
int test = 0;
}
template < typename T>
Foo::~Foo()
{
int test = 0;
}
template class Foo ; // explicit instantiation
//---------------------------------------------------------------
With this approach, we don't have huge headers, and hence the build time will drop. Also, the header files will be "cleaner" and more readable. However, we don't have the benefits of lazy instantiation here (explicit instantiation generates the code for all member functions)
reference: http://www.codeproject.com/KB/cpp/templatesourceorg.aspx
- The type that is created from a template class is called a specialization.
//---------------------------------------------------------------
// in main.cpp
#include "temp.h"
int main()
{
Foo
Foo
return 0;
}
// in temp.h
template < typename T>class Foo
{
public:
Foo() ;
~Foo() ;
Foo( Foo &rhs )
{
int test = 0 ;
};
};
#include "temp.cpp"
template < typename T>
Foo
{
int test = 0;
}
template < typename T>
Foo
{
int test = 0;
}
//---------------------------------------------------------------
With this approach, we don't have huge headers, and hence the build time will drop. Also, the header files will be "cleaner" and more readable. However, we don't have the benefits of lazy instantiation here (explicit instantiation generates the code for all member functions)
Comments
Post a Comment