简体   繁体   中英

Having trouble with C++ variadic template parameters

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM