让我们考虑以下函数:
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()
有一个额外的论点,我真的不喜欢这个想法。你还有其他线索吗?
最佳答案
在我看来,Max Langhof 的解决方案简单而优雅。
不幸的是,它使用仅从 C++17 开始可用的模板折叠。
我提出一个 C++11/C++14 版本,而不是模板折叠,使用初始化未使用数组的老技巧
template <typename ... Args>
void Print (Type const & type, std::string const & message,
Args const & ... arg)
{
using unused = int[];
std::stringstream strstr;
strstr << message << ": ";
(void)unused { 0, (strstr << arg << ", ", 0)... };
std::string toLog = strstr.str();
// Remove last separator characters.
toLog.erase(toLog.end() - 2, toLog.end());
Log(type, strstr.str());
}
关于c++ - 使用模板可变参数函数将多个参数传递给另一个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51761209/