Difference between revisions of "CPP/Templates/ClassTemplateExplicitInstantiation"

From ProgrammingExamples
< CPP
Jump to: navigation, search
(Created page with '==ClassTemplate.cpp== <source lang="cpp"> #include <iostream> #include <vector> #include "Point.h" using namespace std; int main(int argc, char* argv[]) { Point<double> A; …')
 
(Point.h)
Line 36: Line 36:
 
};
 
};
  
//must put the definition here
+
#ifdef NO_EXPLICIT_INSTANTIATION
 +
 
 +
//must put the definition here to avoid explicit instantiation
 
template <typename T>
 
template <typename T>
 
double Point<T>::Add()
 
double Point<T>::Add()
Line 42: Line 44:
 
return 2.0 + 4.3;
 
return 2.0 + 4.3;
 
}
 
}
 +
 +
#endif
  
 
#endif
 
#endif

Revision as of 23:09, 30 November 2010

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;
 
/*
//cannot put the definition here
template <typename T>
double Point<T>::Add()
{
	return 2.0 + 4.3;
}
*/