Skip to content

Instantly share code, notes, and snippets.

@CodingEddie
Created January 9, 2019 05:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save CodingEddie/49edfad9efca80897fb38d954091f425 to your computer and use it in GitHub Desktop.
Save CodingEddie/49edfad9efca80897fb38d954091f425 to your computer and use it in GitHub Desktop.
template class error
// declaration
template<typename T>
friend std::ostream& operator<<(std::ostream& os, const LiteMatrix<T>& rhs); // works
template<typename T>
friend std::ostream& operator<<(std::ostream& os, const LiteMatrix& rhs); // compiler error
// cannot access private member declared in class
friend std::ostream& operator<<(std::ostream& os, const LiteMatrix& rhs); // linker error
friend std::ostream& operator<<(std::ostream& os, const LiteMatrix<T>& rhs); // linker error
// implementation
template<typename T>
std::ostream& operator<<(std::ostream& os, const LiteMatrix<T>& rhs)
{
for (size_t i = 0; i < rhs.m_rows; ++i)
{
for (size_t j = 0; j < rhs.m_cols; ++j)
os << std::setw(6) << std::fixed << std::setprecision(2) << rhs.m_mat[i * rhs.m_cols + j] << ' ';
os << '\n';
}
return os;
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
// other option is all in the class declaration
// this works
friend std::ostream& operator<<(std::ostream& os, const LiteMatrix& rhs)
{
for (size_t i = 0; i < rhs.m_rows; ++i)
{
for (size_t j = 0; j < rhs.m_cols; ++j)
os << std::setw(6) << std::fixed << std::setprecision(2) << rhs.m_mat[i * rhs.m_cols + j] << ' ';
os << '\n';
}
return os;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment