Thanks in advance for your attention!
I had written a simple linear algebra library that includes implementations for vetcor, point, and matrix classes. I had added the prototypes of the friend functions such as << , * , + , - operations in a separate header file named linearalgebra.h. This file was included in all class header files, only forward declared the classes and provided the implementation of the friend functions in a source file to avoid adding several std includes in my library namespace. Expectedly, using the linearalgebra.h file alone raised “incomplete class” exception. However, when I changed the classes to be based on template types, friend functions could only be implemented inside linearalgebra.h where there is no implementation for the classes. I am puzzled how without having access to the class implementation this works with template classes while it did not work when there was no templates? How does g++ compiler treat my code?
Here is some code snippet
linearalgebra.h file
namespace Linearalgebra{
template<typename T> class Matrix;
template<typename T> class Point;
template<typename T>
Point<T> operator*(const Matrix<T> &t, const Point<T> &p) {
//implementation for operator* which has access to private members
//of matrix and point class
return point;
}
}//end of namespace
point.h file
#include "linearalgebra.h"
namespace Linearalgebra{
template<typename T>
class Point{
// class implementation ……………….
//friend function declaration
template<typename U>
Point<U> operator*(const Matrix<U>& t, const Point<U>& p);
};
}//end of namespace
matrix.h file
#include "linearalgebra.h"
namespace Linearalgebra{
template<typename T>
class Matrix{
// class implementation ……………….
//friend function declaration
template<typename U>
Point<U> operator*(const Matrix<U>& t, const Point<U>& p);
};
}//end of namespace