ocramot
ocramot

Reputation: 1391

C++ use operator<< output as parameter in function

I'm new to c++. I've seen a bazillion examples of the use of the operator<< where the output is sent to cout or cerr. Most classes overload this operator to have a human readable output in console, for instance in this example:

ostream& operator<<(ostream& os, const Date& dt)
{
    os << dt.mo << '/' << dt.da << '/' << dt.yr;
    return os;
}

It allows to do this:

Date dt(5, 6, 92);
cout << "The date is " << dt;

Now, I want to do the same thing, but I want to output to a file, not to a console. I'm using Boost, and I'm following the example here:

logging::record rec = lg.open_record();
if (rec)
{
    logging::record_ostream strm(rec);
    strm << "Hello, World!";
    strm.flush();
    lg.push_record(boost::move(rec));
}

The example is fine, but I want to put this code into a function. This is my code so far:

namespace logging = boost::log;

void log(severity_level level, std::string message)
{
    src::severity_logger<severity_level> lg;
    logging::record rec = lg.open_record(keywords::severity = level);
    if (rec)
    {
        logging::record_ostream strm(rec);
        strm << message;
        strm.flush();
        lg.push_record(boost::move(rec));
    }
}

Of course this works for string, but it won't work with the Date from the example above:

Date dt(5, 6, 92);
log(severity_level::info, "The date is "); // No problem here
log(severity_level::info, dt); // Error, dt is not of type string

How can I do something like that?

Upvotes: 1

Views: 74

Answers (1)

VLL
VLL

Reputation: 10165

To support multiple types, make log() a template function. Problem with your original code is that you only overloaded operator<<, and you have not overloaded any conversion operators.

template<typename T>
void log(severity_level level, const T& message)
{
    // ...
    strm << message;
    // ...
}

Upvotes: 1

Related Questions