I have a class that wraps logic for matrix management. Meanwhile I have a set of methods specialized in handling some important time spending matrix manipulation operations (like LU factorization and so on).
The class uses the functions defined in that file. That file needs to have access to that class’ elements. I need to make those specialized methods friends of the above-mentioned class. This causes me to include one header in each other header.
My problem
The situation I described before is coded here as follows. The first code refers to mat.hpp.
#ifndef MAT_HPP
#define MAT_HPP
#include "operations.hpp"
namespace nsA {
template <typename T>
// Templated class because matrices can be real or complex
class mat {
// Members...
friend template <typename U>
void exec_lu(const mat<U>& in, const mat<U>& out);
// Members...
} /* class end */
}
#endif
#endif
The second file is operations.hpp
#ifndef OPERATIONS_HPP
#define OPERATIONS_HPP
#include "mat.hpp"
namespace nsA {
namespace nsB {
template <typename T>
void exec_lu(const mat<T>& in, const mat<T>& out);
}
}
#endif
The problem is that the compiler starts complaining.
Note
Consider please that if I comment the friend declaration in mat.hpp but leave the inclusions, the compiler tells me that in ‘operations.hpp’ type mat is not defined!
If also comment the inclusion in mat.hpp and keep friend declaration commented as well, the compiler is ok!
How to work on this?
Thankyou
You can do this by just adding a couple of forward declarations… But you can even do better with a bit more code:
The main difference between this approach and yours (other than fixing the syntax limitations) is that in this approach a single instantiation of
exec_luis granted access tomat<T>, in particular the instantiation that needs access to it. In your code (after fixing), all specializations ofexec_luwould have access to any specialization ofmat(i.e.exec_lu<int>could accessmat<int>private members, but alsomat<double>…) and you probably don’t want that.For a longer description of the different options to declare friends of a template, read this answer to a related question.