I have a class with an enum in it and I want to overwrite the >> and << operators, but I don't know how to do it while also modifying the istream and the ostream.
Piece.h
#pragma once
#include <cstdint>
#include <string>
#include <unordered_map>
class Piece
{
public:
enum class Color {
red, black, yellow, white, undefined
};
Piece();
Piece(uint8_t value, Color m_color);
Piece(const Piece& toBeCopied);
std::string getStringFromEnum(Color color) const;
private:
uint8_t m_value;
bool m_wasUsed;
std::string m_name;
Color m_color;
void switchWasUsed();
bool operator=(const Piece& toBeCompared);
friend std::istream& operator>>(std::istream& is, Piece& toBeReadInto);
friend std::ostream& operator<<(std::ostream& is, const Piece& toBeShown);
};
Piece.cpp
#include "Piece.h"
Piece::Piece():
m_value(0),
m_color(Color::undefined),
m_wasUsed(0),
m_name(std::to_string(m_value) + getStringFromEnum(m_color))
{
}
Piece::Piece(uint8_t value, Color color) :
m_value(0),
m_color(color),
m_wasUsed(0),
m_name(std::to_string(m_value) + getStringFromEnum(m_color))
{
if (value > 0 && value <= 15)
{
m_value = value;
}
}
Piece::Piece(const Piece& toBeCopied):
m_value(toBeCopied.m_value),
m_name(toBeCopied.m_name),
m_color(toBeCopied.m_color),
m_wasUsed(toBeCopied.m_wasUsed)
{
}
std::string Piece::getStringFromEnum(Color color)
{
switch (color)
{
case Color::red:
return std::string("red");
case Color::white:
return std::string("white");
case Color::black:
return std::string("black");
case Color::yellow:
return std::string("yellow");
case Color::undefined:
return std::string("undefined");
}
}
void Piece::switchWasUsed()
{
m_wasUsed = !m_wasUsed;
}
bool Piece::operator=(const Piece& toBeCompared)
{
return this->m_color == toBeCompared.m_color && this->m_value == toBeCompared.m_value;
}
Source.cpp
#include <iostream>
#include "Piece.h"
std::istream& operator>>(std::istream& is, Piece& toBeReadInto)
{
is >> toBeReadInto.m_value >> toBeReadInto.m_color; //error
}
std::ostream& operator<<(std::ostream& os, const Piece& toBeShown)
{
os << toBeShown.m_value << toBeReadInto.m_color; //error
/*option1, but now I don't really modify the ostream*/
toBeShown.getStringFromEnum(toBeReadInto.m_color);
return os;
}
int main()
{
return 0;
}
I might be able to do it using helper functions, like I did in operator<<, but I want to learn if there's any other way to do it so the i/o streams are modified.
So, is there any way to modify the istream/ostream without any helper function? Just like I would normally do with a non-enum field?