CPP/Templates/ClassTemplateExplicitInstantiation

From ProgrammingExamples
< CPP
Revision as of 23:12, 30 November 2010 by Mikael.s.persson (Talk | contribs)

Jump to: navigation, search

ClassTemplate.cpp

#include <iostream>
#include <vector>
 
#include "Point.h"
 
using namespace std;
 
int main(int argc, char* argv[])
{
  Point<double> A;
 
  cout << A.Add( ) << endl;
  return 0;
}

Point.h

#ifndef POINT_H
#define POINT_H
 
#include <vector>
 
using namespace std;
 
template <typename T>
class Point
{
	T x,y,z;
 
public:
	double Add();
};
 
#ifdef NO_EXPLICIT_INSTANTIATION
 
//must put the definition here to avoid explicit instantiation
template <typename T>
double Point<T>::Add()
{
	return 2.0 + 4.3;
}
 
#endif
 
#endif

Point.cpp

#include "Point.h"
 
#include <vector>
 
using namespace std;
 
#ifndef NO_EXPLICIT_INSTANTIATION
 
//can put the definition here, however... (see below)
template <typename T>
double Point<T>::Add()
{
	return 2.0 + 4.3;
};
 
//... you will be required to instantiate all classes you might use from this template.
template class Point<double>;
template class Point<float>;
//... etc.
 
 
#endif