我不知道这是否可以通过可变参数模板,可变参数marcos甚至元编程来实现。
基本上我有一个这样的记录对象:
LOG << "This is the value of variable X: " << varaibleX;
但我也希望能够像函数一样使用LOG
LOG ( "This is the value of variable X: ", variableX);
但参数的数量可能会有所不同。 (假设他们的呼叫可以转换为流)
我在看LOG ( ... )
,但真的不确定如何扩展参数。
所以让我们说有人写了
LOG(X, Y, Z);
我希望将其扩展为:
LOG << X << Y << Z;
可以这样做吗?
答案 0 :(得分:1)
这可以使用如下的可变参数模板完成。由于不清楚你的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;
}
您需要使用 c ++ 0x 支持编译它。使用g ++,可以使用 - std = c ++ 0x 标志来完成。