I want to be able to print (or not to print) the std:ostream
in my C++ application depends on some condition. Actually I want to use it for debugging but perhaps this will be used for other purposes as well. The condition is runtime variable so I cannot use the C++ preprocessor.
So far I've created a class for that:
#include <iostream>
class Print
{
public:
Print();
template<typename T>
Print& operator<<(T t)
{
if(Print::AllowPrint)
{
std::cout << t;
}
return *this;
}
static bool AllowPrint;
};
This is supposed to be used as following:
Print() << "some message" << std::endl; // will be printed
...
Print::AllowPrint = false;
...
Print() << "some another message" << std::endl; // will not be printed
But I have some strange compiling error:
error: no match for ‘operator<<’ (operand types are ‘Print’ and ‘<unresolved overloaded function type>’)
Print() << "some message" << std::endl;
~~~~~~~~~~~~~~~~~~~~~~~~~~^~~~~~~~~~~~
As I understand the problem is std::endl
. I can't understand what a problem and what have I do to avoid that.
Update:
I've folloved the answer provided by @Yksisarvinen and added the following:
typedef std::basic_ostream<char, std::char_traits<char> > CoutType;
typedef Print& (*StandardEndLine)(CoutType&);
Print& operator<<(StandardEndLine manip)
{
manip(std::cout);
return *this;
}
static Print& endl(Print& stream)
{
std::cout << std::endl;
return stream;
}
but that still doesn't work as expected. I get the same error. Btw that works:
Print() << "some message" << Print::endl;
but that not what I want, I need std::endl
instead
Update 2
changing
typedef Print& (*StandardEndLine)(CoutType&);
to
typedef std::ostream& (*StandardEndLine)(CoutType&);
solved the issue, thanks to @0x499602D2.
Now I can work with it as expected. Thanks guys!