更大宏结构的有线输出
wired output of a bigger macro construct
我使用宏来研究日志记录机制:
#define LOGFATAL 1 // very serious errors
#define TOSTRING(s) dynamic_cast< std::ostringstream & >((std::ostringstream() << s ) ).str()
#define LOG_TRANSFER(t, s) "[" << t << "] " << s
void inline print_log(const char *level, const std::string& value)
{
std::cout << "[" << timestamp() << "]["<< level << "]" << value << std::endl;
}
#ifdef DEBUGGING
#define DEBUG_OUT(l, s) print_log(l, TOSTRING(s));
#else
#define DEBUG_OUT(s, l)
#endif
#if DEBUGGING >= LOGFATAL
#define LOG_FATAL(s) DEBUG_OUT("FATAL", s)
#else
#define LOG_FATAL(s)
#endif
我用他的方式:LOG_TRACE(LOG_TRANSFER(ptr,"MemoryManager>allocate")LOG_TRACE("MemoryManager>size:"<<active_list.size())
gcc的作用是:
print_log("TRACE", dynamic_cast< std::ostringstream & >((std::ostringstream() << "[" << ptr << "] " << "MemoryManager > allocate " ) ).str());
print_log("TRACE", dynamic_cast< std::ostringstream & >((std::ostringstream() << "MemoryManager > size : " << active_list.size() ) ).str());
这在我看来还可以,但我得到了以下输出:
[0 s][TRACE]0x80940d40x9988ea8] MemoryManager > allocate
[0 s][TRACE]0x80941e01
错误在哪里?
问题在于:
dynamic_cast< std::ostringstream & >((std::ostringstream() << s )).str()
或者更准确地说:
std::ostringstream() << s
原因是表达式std::ostringstream()
是一个临时对象,您不能在其上调用非成员重载<<
,因为所有非成员<<
重载都将第一个参数作为std::ostream&
,这是非常量引用。但是临时引用不能绑定到非常量引用。因此,当您想要打印char*
时,会调用一个成员函数,该函数将转换为void*
并打印地址。
你需要做一个小黑客。将临时对象(右值)转换为引用类型(左值)为:
std::ostringstream().flush() << s
我为什么要那样叫flush()
你可以在一个临时对象上调用一个成员函数。我选择flush()
是因为它返回std::ostream&
,这是一个非常量引用,也是我们所需要的。
它的区别在于:
std::ostringstream() << "nawaz" ; //it prints the address of "nawaz".
std::ostringstream().flush() << "nawaz" ; //it prints "nawaz"
第一个调用打印地址的成员operator<<
,第二个调用打印c字符串的非成员operator<<
。这就是幕后的不同。
所以试试这个:
dynamic_cast< std::ostringstream & >((std::ostringstream().flush() << s )).str()
这应该行得通。
此外,我建议在这里使用static_cast
,正如您已经知道的类型:
static_cast< std::ostringstream & >((std::ostringstream().flush() << s )).str()
它不依赖于RTTI。
相关文章:
- 介子复制/安装头文件到输出目录并保持文件夹结构
- 调用 cout 时如何在结构中输出常量文本?
- 如何使用函数的输出初始化 const 数组结构字段?
- C++可以输出一个结构的内存地址吗
- 使用文件和结构读取数据并输出数据
- CMAKE-输出目录结构和QML模块
- 如何使用结构分析此代码的输出
- boost :: Spirit :: Karma语法:逗号从结构上划定了带有选件属性的输出
- 如何输出属于向量数组的结构字符串
- C++ 如何将结构化 git 日志的输出解析为对象
- 将在 C++ 中输出多维数组内容的 for 循环的结构是什么
- 试图通过结构类型的向量,但没有控制台输出
- 如何在 c++ 中使用二进制文件输入/输出读取/写入结构的字符串类型成员
- C :在结构中以零为零的输出
- 输出用户定义的结构使用boost ::日志
- 将值输入到结构数组 + 打印输出
- 值语义与具有大数据结构的输出参数
- 输出结构的枚举返回负数
- 如何在编译时输出结构体中成员的偏移量(C/ c++)
- 使用位字段输出结构大小