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

Recommended Answers

All 9 Replies

I'm not sure I understand your question. Why can't you just #include "Point.h" ? I do not see anything circular here.

////// 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?

> Then if I include Point in Tools is that not a problem?

I don't think it's a problem. Have you tried it? If so, and if it doesn't work, then post the entire code.

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?

I don't know anything about .txx files.

.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 ...

Just build it like you would build a class library ...
Note: Creating a C++ library depends from compiler to compiler ...

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.