Negative Zero
Negative Zero

Reputation: 1224

Accepting variable number of arguments for logger

I don't know if this can be achieved through variadic template, variadic marcos or even maybe metaprogramming.

Basically I have a logging object like this:

LOG << "This is the value of variable X: " << varaibleX;

but I also want this to be able to use LOG like a function

LOG ( "This is the value of variable X: ", variableX);

but the number of argument can be varying. (assuming they call can be converted into streams)

I was looking at LOG ( ... ), but really not sure how to expand the arguments.

So let's say someone wrote

LOG(X, Y, Z);

and I want to expand this into:

LOG << X << Y << Z;

Can this be done?

Upvotes: 2

Views: 2317

Answers (1)

JaredC
JaredC

Reputation: 5300

This can be done with variadic templates like below. Since its not clear what your LOG object is, I omitted the code to actually call LOG(...), but you should be able to port this do what you need:

#include <iostream>

/**
 * A specialization to stream the last argument 
 * and terminate the recursion. 
 */
template<typename Stream, typename Arg1>
Stream & DoLog(Stream & stream, const Arg1 & arg1)
{
   return (stream << arg1);
}

/** 
 * Recursive function to keep streaming the arguments 
 * one at a time until the last argument is reached and 
 * the specialization above is called. 
 */
template<typename Stream, typename Arg1, typename... Args>
Stream & DoLog(Stream & stream, const Arg1 & arg1, const Args&... args)
{
   return DoLog((stream << arg1), args...);
}

int main()
{
   DoLog(std::cout, "First ", 5, 6) << " Last" << std::endl;
}

You'll need to compile this with c++0x support. With g++, this can be done using the --std=c++0x flag.

Upvotes: 1

Related Questions