Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/147.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 接受记录器的可变参数数_C++_Variadic Functions - Fatal编程技术网

C++ 接受记录器的可变参数数

C++ 接受记录器的可变参数数,c++,variadic-functions,C++,Variadic Functions,我不知道这是否可以通过可变模板、可变marcos甚至元编程来实现 基本上我有这样一个日志对象: LOG << "This is the value of variable X: " << varaibleX; 但争论的数量可能会有所不同。(假设它们的调用可以转换为流) 我正在查看LOG(…),但确实不知道如何扩展参数 假设有人写了 LOG(X, Y, Z); 我想把它扩展到: LOG << X << Y << Z; LOG这可以通

我不知道这是否可以通过可变模板、可变marcos甚至元编程来实现

基本上我有这样一个日志对象:

LOG << "This is the value of variable X: " << varaibleX;
但争论的数量可能会有所不同。(假设它们的调用可以转换为流)

我正在查看
LOG(…)
,但确实不知道如何扩展参数

假设有人写了

LOG(X, Y, Z);
我想把它扩展到:

LOG << X << Y << Z;

LOG这可以通过如下可变模板完成。由于不清楚您的日志对象是什么,我省略了实际调用LOG(…)的代码,但您应该能够移植它来执行您需要的操作:

#include <iostream>

/**
 * A specialization to stream the last argument 
 * and terminate the recursion. 
 */
template<typename Stream, typename Arg1>
Stream & DoLog(Stream & stream, const Arg1 & arg1)
{
   return (stream << arg1);
}

/** 
 * Recursive function to keep streaming the arguments 
 * one at a time until the last argument is reached and 
 * the specialization above is called. 
 */
template<typename Stream, typename Arg1, typename... Args>
Stream & DoLog(Stream & stream, const Arg1 & arg1, const Args&... args)
{
   return DoLog((stream << arg1), args...);
}

int main()
{
   DoLog(std::cout, "First ", 5, 6) << " Last" << std::endl;
}
#包括
/**
*流式处理最后一个参数的专门化
*并终止递归。
*/
模板
溪流和溪流(溪流和溪流,常数Arg1和Arg1)
{

return(stream)
LOG(“Blargh:”是的,我认为这会起作用。所以日志函数会变成递归函数调用,对吗?
#include <iostream>

/**
 * A specialization to stream the last argument 
 * and terminate the recursion. 
 */
template<typename Stream, typename Arg1>
Stream & DoLog(Stream & stream, const Arg1 & arg1)
{
   return (stream << arg1);
}

/** 
 * Recursive function to keep streaming the arguments 
 * one at a time until the last argument is reached and 
 * the specialization above is called. 
 */
template<typename Stream, typename Arg1, typename... Args>
Stream & DoLog(Stream & stream, const Arg1 & arg1, const Args&... args)
{
   return DoLog((stream << arg1), args...);
}

int main()
{
   DoLog(std::cout, "First ", 5, 6) << " Last" << std::endl;
}