Hi friends,
Can you pls tell me about "explicit template instantiation". Suppose I have a simple program :

1. File : TClass.h

#ifndef CTCLASS_H
#define CTCLASS_H

template<class T>
class CTClass
{
public:
	CTClass(T t1, T t2);
	~CTClass();
	T add();
private:
	T cm_T1;
	T cm_T2;
};

template<class T>
CTClass<T>::CTClass(T t1,T t2)
:cm_T1(t1),cm_T2(t2)
{
}

template<class T>
CTClass<T>::~CTClass()
{
}

template<class T>
T CTClass<T>::add()
{
	return cm_T1 + cm_T2;
}

#endif

And in main.cpp

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

using namespace std;

int main()
{
	CTClass<int> l_aCTClass_int(10,20);
	int sum = l_aCTClass_int.add();

	cout<<"sum :: "<<sum<<endl;

	return 0;
}

This is an implicit template instantiation. Now pls tell how and why I can use "explicit template instantiation" in the above example.

Thanx,
Amit

Recommended Answers

All 2 Replies

>> how I can use "explicit template instantiation" in the above example.
an explicit instantiation directive consists of the keyword template followed by a declaration of the version to be instantiated. for example,

template std::string CTClass< std::string >::add() ;

is an explicit intantiation of the member function.
all the members of a class template can be explicitly instantiated by explicitly instantiating the class template. eg.

template class CTClass< double > ;

>> why would I use "explicit template instantiation" ?
there are two valid reasons:
a. while writing/testing template code, it is a good idea to explicitly instantiate the template you have written for a few types. unless a template is instantiated, some errors which are present in the template code may not be detected by the compiler.
b. when there is a large code base with a number of templated types, automatic template instantiation in multiuple translation units can increase build times. manually instantiating certain template specializations in a single location and inhibiting the instantiation in all other translation units can mitigate this.

a third reason is that many (most) compilers do not support the export of templates; if we know that only a few versions of a template are required, we can work around this limitation by explicitly instantiating the template in the translation unit where it is defined and only declaring it in other translation units. however, this assumes that the decorated (mangled) names for an explicitly instantiated template is identical to that generated for an implicit instantiation. this may not be true for all compilers.

Thanx Vijayan for the reply.

Amit

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.