0

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
Harsha J K
  • 197
  • 1
  • 1
  • 17
  • Please provide a [mcve]. – Passer By Apr 03 '18 at 04:42
  • The template is expanded to real honest to goodness code as needed around the given, or deduced, parameters. If nothing makes use of the template, absolutely nothing happens. You might also want to read [Why can templates only be implemented in the header file?](https://stackoverflow.com/questions/495021/why-can-templates-only-be-implemented-in-the-header-file) – user4581301 Apr 03 '18 at 04:46
  • Thanks. That makes sense when I see this code works. Bu, how does that affect the compilation units and the dependencies between the files? Because this example shows that the dependencies are obviously neglected. – Saeid Zarrinmehr Apr 03 '18 at 05:05
  • @user4581301 That link was very helpful. Thanks for sharing that with me. – Saeid Zarrinmehr Apr 03 '18 at 16:17

0 Answers0