简体   繁体   English

C ++可变参数模板参数遇到问题

[英]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. sizeof...(Rest) == 0将调用没有参数的print() ,这需要上面的基本情况重载。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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