Move template functions to a .cpp file
According to this:
http://www.parashift.com/c++-faq-lite/templates.html#faq-35.13
One way to keep only the function declaration in the .h file is to do this
////////// file: Tools.h
#include <iostream>
#include <vector>
using namespace std;
template <typename T> T Sum(vector<T> &V);
///////// file: Tools.cpp
#include "Tools.h"
#include <iostream>
#include <vector>
using namespace std;
template <typename T>
T Sum(vector<T> &V)
{
T sum = static_cast<T>(0.0);
for(unsigned int i = 0; i < V.size(); i++)
sum += V[i];
return sum;
}
//this is the key line to tell the compiler to actually make this function for unsigned int
template unsigned int Sum<unsigned int>(vector<unsigned int> &V);
However, what if you want this function for a type that Tools does not know about? ie
template Point Sum<Point>(vector<Point> &V);
will not work because Point has not been defined. If you make Tools depend on Point, but Point already depends on Tools, then there is a circular problem.
Any suggestions?
Thanks,
Dave
daviddoria
Posting Virtuoso
1,996 posts since Feb 2008
Reputation Points: 437
Solved Threads: 204
////// file: Point.h
#include "Tools.h"
class Point
{
public:
double x,y,z;
void OutputSum()
{
// do something using a function from Tools here
}
};
Then if I include Point in Tools is that not a problem?
daviddoria
Posting Virtuoso
1,996 posts since Feb 2008
Reputation Points: 437
Solved Threads: 204
It does work - but I didn't really want to do that anyway lol, so let me rephrase - is there any way to do this that doesn't involve having to add those two lines (the declaration with specific type and the include) to the .cpp? I've seen people use .txx files - is this what those are for?
daviddoria
Posting Virtuoso
1,996 posts since Feb 2008
Reputation Points: 437
Solved Threads: 204
.TXX: DataPerfect Text Storage
(A file format to store ASCII-only characters)
Are your sure it was '.TXX' and not '.CXX'?
'.CXX' is a valid C++ extension ...
tux4life
Nearly a Posting Maven
2,350 posts since Feb 2009
Reputation Points: 2,134
Solved Threads: 243
daviddoria
Posting Virtuoso
1,996 posts since Feb 2008
Reputation Points: 437
Solved Threads: 204
Just build it like you would build a class library ...
Note: Creating a C++ library depends from compiler to compiler ...
tux4life
Nearly a Posting Maven
2,350 posts since Feb 2009
Reputation Points: 2,134
Solved Threads: 243