Scorb
Scorb

Reputation: 1840

overload stream operator for function

I am curious if it is possible to overload a << stream operator for a function?

I am using OutputDebugString on windows to write to the log, and it only accepts strings.

I am wondering if I can write a function in c++ where I could wrap OutputDebugString and do the following

MyLogFuntion() << string << int << char;

Upvotes: 1

Views: 534

Answers (2)

Motti
Motti

Reputation: 114695

You can return an object from your function that has operator << and then do the logging in the object's destructor. Then when you call MyLogFunction() it will create a temporary object which will store all the data inserted into it and then output it when the object is goes out of scope at the end of the statement.

Here's an example (without The logger function which is actually redundant)

#include <iostream>
#include <sstream>


class Logger {
    std::stringstream ss;
public:
    ~Logger() {
      // You want: OutputDebugString(ss.str()); 
      std::cout<< ss.str(); 
    }

    // General for all types supported by stringstream
    template<typename T>
    Logger& operator<<(const T& arg) {
       ss << arg;
       return *this;
    }

    // You can override for specific types
    Logger& operator<<(bool b) {  
       ss << (b? "Yep" : "Nope");
       return *this;
    }
};


int main() {
    Logger() << "Is the answer " << 42 << "? " << true;
}

Output:

Is the answer 42? Yep

Upvotes: 2

mindriot
mindriot

Reputation: 5668

You cannot provide overloads in the way you would like to.

If the method you have to use (OutputDebugString in your case) forces you to provide a std::string (or similar) parameter, you'll have to provide that parameter somehow. One way is to use a std::stringstream, stream into that, and then pass the result to OutputDebugString:

std::stringstream ss;
ss << whatever << " you " << want << to << stream;
OutputDebugString(ss.str());

You could also dump this into a macro if you really want things more compact:

#define OUTPUT_DEBUG_STRING(streamdata)   \
  do {                                    \
    std::stringstream ss;                 \
    ss << streamdata;                     \
  } while (0)

And then write

OUTPUT_DEBUG_STRING(whatever << " you " << want << to << stream);

Another alternative is to write a more complex wrapper class around OutputDebugString which provides stream operators. But that is probably not going to be worth the effort.

Upvotes: 0

Related Questions