I'm writing a sparse matrix class, and I want to output the sparse matrix by overloading operator<<.
I'm wondering how to enable a friend function of SMatrix (operator<<) directly (not by some interface) access private data members of TriTuple? Note that SMatrix is meanwhile a friend class of TriTuple. See code as follows.
// tri-tuple term for sparse matrix by the form <row, col, value>
template<typename T>
class TriTuple {
template<typename U> friend class SMatrix;
// enable friend of SMatrix access private members of TriTuple
// declaring like this? feasible in VS2019, but not in gcc
template<typename U>
friend std::ostream& operator<<(std::ostream& os, const SMatrix<U>& M);
private:
size_t _row, _col;
T _val;
public:
//...
};
// sparse matrix
template<typename T>
class SMatrix {
template<typename U>
friend std::ostream& operator<<(std::ostream& os, const SMatrix<U>& M);
private:
size_t _rows, _cols;// # of rows & columns
size_t _terms; // # of terms
TriTuple<T>* _arr; // stored by 1-dimensional array
size_t _maxSize;
public:
//...
};
template<typename U>
std::ostream& operator<<(std::ostream& os, const SMatrix<U>& M)
{
M.printHeader();
for (size_t i = 0; i < M._terms; ++i) {
os << M._arr[i]._row << "\t\t" << M._arr[i]._col << "\t\t" << M._arr[i]._val << '\n';
}
return os;
}
It can successfully compile & run in VS2019 (likely C++17), but failed to compile in gcc (currently only c++11 is available). Is that c++ standard version's problem? (It refers "ISO C++ forbids declaration of ..." ) And how should I improve the declarations? See error messages in following picture. gcc error_msg Thank you awesome guys in advance :-)