I'm currently trying to create a template class in C++ and i originally had code that worked with a header file and a CPP file however now that im trying to move my functions from the CPP file to the header file i'm getting some errors. I have two auxiliary functions to stream in and out to the console and the class parameter in the function is showing an error.
ostream& operator<<(ostream& sout, Grid& grid)
{
grid.SaveGrid(sout);
}
void operator>>(istream& sin, Grid &grid)
{
grid.LoadGrid(sin);
}
This is how they originally looked and worked before changing my class to a template class.
The part of the parameters above that doesn't work is this. "Grid &grid"
FULL CODE
#pragma once
#include <fstream>
using namespace std;
template<class T>
class Grid
{
public:
//Grid();
//~Grid();
Grid::Grid()
{
}
Grid::~Grid()
{
}
//void LoadGrid(const char filename[]);
//void LoadGrid(istream& sin);
void Grid<T>::LoadGrid(const char filename[])
{
ifstream file(filename);
for (int y = 0; y < 9; y++) {
for (int x = 0; x < 9; x++)
{
file >> m_grid[x][y];
}
}
file.close();
}
void Grid<T>::LoadGrid(istream& sin)
{
for (int y = 0; y < 9; y++) {
for (int x = 0; x < 9; x++)
{
sin >> m_grid[x][y];
}
}
}
//void SaveGrid(const char filename[]);
//void SaveGrid(ostream& sout);
void Grid<T>::SaveGrid(const char filename[])
{
ofstream file(filename);
for (int y = 0; y < 9; y++) {
for (int x = 0; x < 9; x++)
{
file << m_grid[x][y] << " ";
}
file << endl;
}
file.close();
}
void Grid<T>::SaveGrid(ostream & sout)
{
for (int y = 0; y < 9; y++) {
for (int x = 0; x < 9; x++)
{
sout << m_grid[x][y] << " ";
}
sout << endl;
}
}
private:
T m_grid[9][9];
};
ostream& operator<<(ostream& sout, Grid<T>& grid)
{
grid.SaveGrid(sout);
}
void operator>>(istream& sin, Grid<T>& grid)
{
grid.LoadGrid(sin);
}
does not work because
Grid
is a class template, not a class. You need to use:To make it
const
correct, useNote that, you'll need to make
SaveGrid
aconst
member function for the above change to work.Make similar changes to the other function.