在扩展中创建字符串流的日志宏
Logging macro with stringstream creation in expansion
我正在努力实现这个目标:
#include <iostream>
#include <sstream>
void log(
const char* argFile,
int argLineNb,
const char* argFunction,
std::stringstream& argString) {
std::cout << argFile << ":" << argLineNb << " " << argFunction
<< " " << argString.str()<< std::endl;
}
/**
* brief Macro declarations
*/
#define LOG_TEST(f)
log(__FILE__, __LINE__,
__FUNCTION__, (std::ostringstream << f))
int main(int argc, char** argv) {
LOG_TEST("HELLO");
LOG_TEST("HELLO" << " !");
return 0;
}
问题是,我真的不知道如何做到这一点,因为我得到以下错误:
类型'std::stringstream&{又称std::basic_ostream::__ostream_type{又称std::basic_ostream
我不知道是否有一个更简单的方法来做到这一点与boost…
来源:http://coliru.stacked-crooked.com/view?id=222cbb23ea5162b16378b13a24fceb9e-4f0e144d2529f0880899ab58231ebbe3
主要问题是:(std::stringstream() << f)
如果你阅读std::stringstream
的operator<<(...)
的参考资料,你会发现它继承自std::ostream
问题是operator<<(...)
返回std::ostream
,因此,当您传递(std::stringstream() << f)
时,您实际上是将std::ostream
传递给需要std::stringstream
的函数(因此,ostream中stringstream的无效初始化)
为了达到你想要的效果,你必须修改你的宏的工作方式。试试这样做:
#define LOG_TEST(f)
do { std::stringstream s;
s << f;
log(__FILE__, __LINE__, __FUNCTION__, s);
} while (0)