[Solved] Does the stream operator exist for class member functions?


It can be done easily like this:

#include <iostream>

class A {
  public:
    std::ostream &debug() const {
      std::cerr << "[timestamp]" << "[DEBUG]";
      return std::cerr;   
    }
};

int main()
{
    A a;
    a.debug() << "Test";
}

But the important question here is: Should we implement it in this way? In my opinion, NO!

Because you are thinking that the User of the class will print the logs like this:

int main()
{
    A a;
    a.debug() << "Test" << std::endl;
    a.debug() << "Test2" << std::endl;
}

Output:

[timestamp][DEBUG]Test
[timestamp][DEBUG]Test2

But what if User chooses this way:

int main()
{
    A a;
    auto &out = a.debug();
    out << "Test" << std::endl;
    out << "Test2" << std::endl;
}

Output:

[timestamp][DEBUG]Test
Test2

I would highly recommend not to return stream object. You should use member functions for this purpose.

#include <iostream>

class A {
  public:
    static void debug(const std::string &log) {
      std::cerr << "[timestamp]" << "[DEBUG]" << log << std::endl;
    }
};

int main()
{
    A::debug("Test 1");
    A::debug("Test 2");
}

Output:

[timestamp][DEBUG]Test 1
[timestamp][DEBUG]Test 2

1

solved Does the stream operator exist for class member functions?