1

I am trying to overload operator<< for ostream to do up a writing to log file mechanism. Within CExportFunctions project, I am able to log << "xxx". However, when I tried to perform the same in another project (CCallMethods), I am unable to write into the file. Compilation was okay. No errors. But Entered processMessage() did not get written into the file. Can any one please help?

Project A - CExportFunctions.h:
#ifdef DLLDIR_EX
   #define DLLDIR  __declspec(dllexport)   // export DLL information
#else
   #define DLLDIR  __declspec(dllimport)   // import DLL information
#endif

...

class DLLDIR CExportFunctions
{
public:
    ...

    ofstream stream;
};

Project A - CExportFunctions.cpp:

#include "CExportFunctions.h"

...

//! write to log file
template<typename T> CExportFunctions& operator<<(CExportFunctions& stream, T val)
{
    ...

    stream.stream.open("D:/Logger/logs.txt", ios::out | ios::app);
    stream.stream << << val << std::endl;
    stream.stream.close();

    return stream;
}

//! save scenario dialog
void CExportFunctions::saveScenario()
{
    CExportFunctions log;
    log << "Entered saveScenario()";

    ...
}

Project B - CCallMethods.cpp:

#include "CExportFunctions.h"

void CCallMethods::processMessage()
{
    ...

    CExportFunctions log;
    log.stream << "Entered processMessage()";
}
Wallace
  • 293
  • 1
  • 9
  • 18

1 Answers1

1

You're calling different functions. In your save scenario:

//! save scenario dialog
void CExportFunctions::saveScenario()
{
    CExportFunctions log;
    log << "Entered saveScenario()";

    ...
}

You're actually calling your

template<typename T> CExportFunctions& operator<<(CExportFunctions& stream, T val)

But this the second one:

void CCallMethods::processMessage()
{
    ...

    CExportFunctions log;
    log.stream << "Entered processMessage()";
}

You're calling operator<<(std::ofstream&, const char*)... which doesn't involve opening a file. I think you just meant:

log << "Entered processMessage()";
Barry
  • 286,269
  • 29
  • 621
  • 977
  • Thanks. I can't do `log << "Entered processMessage()"`. It says that **Error: no operator "<<" matches these operands.** Do I have to export the template to be used in another project's class? Perhaps I did not state clearly. `CCallMethods()` is a method from Project B. – Wallace Nov 01 '14 at 15:20
  • Is your templated operator defined in your .cpp file? If so, it's just not visible then. You'd have to move it to the header. – Barry Nov 01 '14 at 15:33