2

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!

folibis
  • 12,048
  • 6
  • 54
  • 97
  • `StandardEndLine` doesn't match `std::endl`. The latter returns `std::basic_ostream&`, not `Print&`. You need `operator<<` overload that takes exactly the type of `std::endl` – Igor Tandetnik Jan 03 '21 at 16:31
  • Change the typedef function type to return `std::ostream&` instead of `Print&` and then you'll be able to use `std::endl`. – David G Jan 03 '21 at 17:06
  • Looks like you just need to read past the first answer. The first answer there is easy to understand, but doesn't do what you exactly wants. (OP accepted it anyway) – user202729 Jan 04 '21 at 01:41

0 Answers0