When I try my own version I am getting
error C2039: 'endl' : is not a member of 'abc' error C2065: 'endl' : undeclared identifier
Here is the code below.
#include <iostream>
#include <stdio.h>
//assume this class uses some proprietary logging system. I just use the wrap the C
//output functions here but assume is a corporate log system
namespace abc {
class log_stream
{
public:
log_stream(const char* filename) {
fp_ = fopen(filename, "w");
}
log_stream& operator<<(short val) { if (fp_) { output_int(val); } return *this; }
log_stream& operator<<(unsigned short val) { if (fp_) { output_int(val); } return *this; }
log_stream& operator<<(int val) { if (fp_) { output_int(val); } return *this; }
log_stream& operator<<(unsigned int val) { if (fp_) { output_int(val); } return *this; }
log_stream& operator<<(long val) { if (fp_) { output_int(val); } return *this; }
log_stream& operator<<(unsigned long val) { if (fp_) { output_int(val); } return *this; }
log_stream& operator<<(const char* val) { if (fp_) { output_string(val); } return *this; }
inline log_stream& endl(log_stream& os) { return os.endl(); }
//etc
log_stream& endl() {
if(fp_)
fputc('\n', fp_);
return *this;
}
private:
void output_int(long v) { fprintf(fp_, "%d", v); }
void output_string(const char* s) { fprintf(fp_, "%s", s); }
FILE* fp_;
};
} //namespace abc
int main() {
abc::log_stream logger("myfile.txt");
//error C2039: 'endl' : is not a member of 'abc', error C2065: 'endl' : undeclared identifier
logger << "number " << 3 << abc::endl;
return 0;
}
UPDATE:
If I add
inline log_stream& endl(log_stream& os) { return os.endl(); }
inside the abc namespace (but outside the class, I then get
error C2678: binary '<<' : no operator found which takes a left-hand operand of type 'abc::log_stream' (or there is no acceptable conversion)
Which is closer (I think) to solving, but not there yet.
UPDATE2.
Well, that was hairy! Here is how I fixed problem for anyone doing anything similar. Thanks Julien.
added these to class:
~log_stream() { if(fp_) fclose(fp_); }
// this is the main one I was missing
abc::log_stream& abc::log_stream::operator<<( log_stream& (*pf)(log_stream&) )
{
return pf(*this);
}
Then outside class:
abc::log_stream& endl( abc::log_stream& log ) { log.endl(); return log; }