【发布时间】:2019-01-16 13:49:34
【问题描述】:
让我们考虑以下函数:
static void Print(const Type& type, const std::string& message, const std::string& variable) {
Log(type, message + ": " + variable);
}
我希望它传递任意数量的变量(我的意思是 std::string & 变量 - 它包含一个变量名),然后通过 Log() 函数一起发送它们,因此,我考虑使用模板可变参数函数(重载的Print())。我会这样定义它:
template <typename Arg, typename ...Args)
static void Print(const Type& type, const std::string& message,
const Arg& arg, const Args&... args);
然后:
Print(type, message, args...);
Log(type, message + ": " + arg);
只是一个想法,这很可能会像这样工作:
-
args...将被传递,Print()函数将被递归调用,直到没有剩下的参数, - 但同时会调用
Log()函数,基本上每次都会记录。
我需要做的是以某种方式记住arg 的值,但这需要使用附加参数调用Print(),我不太喜欢这个想法。你还有其他线索吗?
【问题讨论】:
-
您需要一个支持函数来完成实际工作。任何日志记录前缀都附加到
Print的日志中,然后其他所有内容都由PrintImpl递归处理。 -
我在这里考虑过这种解决方案,虽然它可能不是什么漂亮的东西,但它会起作用。
标签: c++ c++11 templates variadic-templates variadic-functions