在使用 C++ 可变参数模板参数时遇到问题
Having trouble with C++ variadic template parameters
我正在尝试编写一个通用函数来记录一些用于调试的内容,我想这样调用它:
Log("auo", 34); //writes: auo34
Point point;
point.X = 10;
point.Y = 15;
Log(35, point, 10); //writes: 35{10, 15}10
然而,我在参数打包和解包方面遇到了各种各样的问题,我似乎无法掌握它。以下是完整代码:
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...);
}
请问如何修复这些功能?
采用以下简化版本:
void print() {}
template<typename First, typename... Rest>
void print(const First& first, const Rest&... rest)
{
std::cout << first;
print(rest...);
}
当 sizeof...(Rest) == 0
时,将发出不带参数的对 print()
的调用,这需要上面的基本情况重载。
我正在尝试编写一个通用函数来记录一些用于调试的内容,我想这样调用它:
Log("auo", 34); //writes: auo34
Point point;
point.X = 10;
point.Y = 15;
Log(35, point, 10); //writes: 35{10, 15}10
然而,我在参数打包和解包方面遇到了各种各样的问题,我似乎无法掌握它。以下是完整代码:
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...);
}
请问如何修复这些功能?
采用以下简化版本:
void print() {}
template<typename First, typename... Rest>
void print(const First& first, const Rest&... rest)
{
std::cout << first;
print(rest...);
}
当 sizeof...(Rest) == 0
时,将发出不带参数的对 print()
的调用,这需要上面的基本情况重载。