cyclic template classes

I've got a problem with template classes. I have a base class Matrix, from which a dense and a sparse matrix are derived (all three of them are templates). Now I'd like to write a copy operator from the dense to the sparse matrix, and from the sparse to the dense matrix. Since the implementation has to go into the header, I end up with a cyclic inclusion of SparseMatrix.h in DenseMatrix.h and DenseMatrix.h ind SparseMatrix.h, which does not compile.
Any ideas how to solve this problem?

Thanks
JFU
If I understand correctly, you need include guards:

DenseMatrix.h
1
2
3
4
5
6
7
8
9
#ifndef  DENSE_MATRIX_H
#define DENSE_MATRIX_H

#include "SparseMatrix.h"

// code here


#endif 


SparseeMatrix.h
1
2
3
4
5
6
7
8
#ifndef SPARSE_MATRIX_H
#define SPARSE_MATRIX_H

#include "DenseMatrix.h"

// code here

#endif 


See http://www.cplusplus.com/forum/articles/10627/
Last edited on
This is a typical problem and a solution is like the following. Hope it helps.

// "DenseMatrix.h"
#include "DenseMatrixDef.h"
#include "SparseMatrixDef.h"
#include "DenseMatrixImpl.h"

// "SparseMatrix.h"
#include "SparseMatrixDef.h"
#include "SparseMatrixDef.h"
#include "SparseMatrixImpl.h"

// "SparseMatrixDef.h"
template<...>
struct SparseMatrix
{
SparseMatrix(const DenseMatrix<...>& x); // no implementation here
};

// "DenseMatrixDef.h", similar to above

// "SparseMatrixImpl.h"
template<...>
SparseMatrix<...>::SparseMatrix(const DenseMatrix<...>& x)
{
// implementation goes here
}

// "SparseMatrixImpl.h", similar to above
Topic archived. No new replies allowed.