Reputation: 2825
I'm trying to write a generic function for logging some stuff for debugging, and I want to call it for example like so:
Log("auo", 34); //writes: auo34
Point point;
point.X = 10;
point.Y = 15;
Log(35, point, 10); //writes: 35{10, 15}10
However, I'm having all kinds of problems with parameter packing and unpacking, I can't seem to get the hang of it. Below is the full code:
struct Point {
long X, Y;
}
std::ofstream debugStream;
template<typename ...Rest>
void Log(Point first, Rest... params) { //specialised for Point
if (!debugStream.is_open())
debugStream.open("bla.log", ios::out | ios::app);
debugStream << "{" << first.X << ", " << first.Y << "}";
Log(params...);
}
template<typename First, typename ...Rest>
void Log(First first, Rest... params) { //generic
if (!debugStream.is_open())
debugStream.open("bla.log", ios::out | ios::app);
debugStream << first;
Log(params...);
}
How do I fix the functions please?
Upvotes: 2
Views: 230
Reputation: 10425
Take the following simplified version:
void print() {}
template<typename First, typename... Rest>
void print(const First& first, const Rest&... rest)
{
std::cout << first;
print(rest...);
}
When sizeof...(Rest) == 0
a call to print()
with no parameters will be issued which requires the base case overload above.
Upvotes: 4