I am trying to write to file and stdout at the same time within c++ by overloading ofstream
test.h
#pragma once
#include
using
ofstream::operator << (var);
It's your use of ofstream::operator<< as a qualified function call. You're mandating that the function lookup locate a member function of ofstream; the best match that's a member is the one for void*, whereas the specialisation for char* 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:
std::cout.operator<<(var);
This might do it:
static_cast(*this) << var;
because you're still using normal operator syntax (with all the overload resolution that this entails), but doing so with an ofstream as the LHS operand.
I haven't actually tested it, though.
As an aside, your operator<< ought to be a free function too, in order to fit in with this convention.
So:
struct OutputAndConsole : std::ofstream
{
OutputAndConsole(const std::string& fileName)
: std::ofstream(fileName)
, fileName(fileName)
{};
const std::string fileName;
};
template
OutputAndConsole& operator<<(OutputAndConsole& strm, const T& var)
{
std::cout << var;
static_cast(strm) << var;
return strm;
};
I also took the liberty of making some minor syntax adjustments.