1

I'm trying to overload the Insertion Operator. One method works, the other does not - but I'm not sure why, as they seem identical to me. Here's the relevant code (irrelevant sections chopped out):

#include <string>
#include <fstream>

#define UINT        unsigned int

///////////////////////////////////////////////////////////

class Date
{
public:
    // These just return unsigned ints 
    UINT Month();
    UINT Day();
    UINT Year();

    UINT month;
    UINT day;
    UINT year;
};

///////////////////////////////////////////////////////////

class BinaryFileWriter
{
public:
    virtual bool Open(string i_Filename);
    void Write(UINT i_Uint);

private:
    ofstream ofs;
};

template <typename T1>
BinaryFileWriter& operator << (BinaryFileWriter& i_Writer, T1& i_Value)
{
    i_Writer.Write(i_Value);
    return(i_Writer);
}

bool BinaryFileWriter::Open(string i_Filename)
{
    ofs.open(i_Filename, ios_base::binary);
}

void BinaryFileWriter::Write(UINT i_Uint)
{
    ofs.write(reinterpret_cast<const char*>(&i_Uint), sizeof(UINT));
}

///////////////////////////////////////////////////////////

void Some_Function(Date i_Game_Date)
{
    BinaryFileWriter bfw;
    bfw.Open("test1.txt");

    // This works
    UINT month = i_Game_Date.Month();
    UINT day = i_Game_Date.Day();
    UINT year = i_Game_Date.Year();
    bfw << month << day << year;

    // This does not - gives me error 'error C2679: binary '<<' : no operator found which takes a right-hand operand of type 'unsigned int' (or there is no acceptable conversion)  '
    bfw << (m_Game_Date.Month()) << (m_Game_Date.Day()) << (m_Game_Date.Year());

So why does the first output line (where I get the UINT values first, berfore outputting) compile just fine, but not the second (where I use the return values of the date methods as input to my overloaded insertion operator)?

user3236291
  • 133
  • 7

1 Answers1

1

In the first line, you are able use month, day, and year can be converted to INT&.

In the second line, you are using the return values of the member functions. They are temporary objects. They cannot be bound to INT&.

In order to be able to use,

bfw << (m_Game_Date.Month()) << (m_Game_Date.Day()) << (m_Game_Date.Year());

The second argument of the operator<< function must be a T1 const&, not T1&.

template <typename T1>
BinaryFileWriter& operator << (BinaryFileWriter& i_Writer, T1 const& i_Value)
{
    i_Writer.Write(i_Value);
    return(i_Writer);
}
R Sahu
  • 204,454
  • 14
  • 159
  • 270