I am trying to write to file and stdout at the same time within c++ by overloading ofstream
test.h
#pragma once
#include <iostream>
using std::ofstream;
class OutputAndConsole:public ofstream
{
public:
std::string fileName;
OutputAndConsole(const std::string& fileName):ofstream(fileName),fileName(fileName){
};
template <typename T>
OutputAndConsole& operator<<(T var);
};
template <typename T>
OutputAndConsole& OutputAndConsole::operator<<(T var)
{
std::cout << var;
ofstream::operator << (var);
return (*this);
};
test.cpp
OutputAndConsole file("output.txt");
file << "test" ;
The output in the file is
01400930
but in the console is
test
I debugged the code it looks like it is entering into
_Myt& __CLR_OR_THIS_CALL operator<<(const void *_Val)
What am I doing wrong?
The problem
It’s your use of
ofstream::operator<<as a qualified function call. You’re mandating that the function lookup locate a member function ofofstream; the best match that’s a member is the one forvoid*, whereas the specialisation forchar*that prints the actual string contents is a free function (i.e. not a member function).You’ll find the same problem if you do this with
cout, too:The solution
This might do it:
because you’re still using normal operator syntax (with all the overload resolution that this entails), but doing so with an
ofstreamas the LHS operand.I haven’t actually tested it, though.
Conclusion
As an aside, your
operator<<ought to be a free function too, in order to fit in with this convention.So:
I also took the liberty of making some minor syntax adjustments.