如何绕过 << 调用,就好像"#ifndef DEBUG" c++ 中的宏一样?
How to bypass a << calling as if "#ifndef DEBUG" macro in c++?
我为自己编写了一个小的logging-lib,它接受两种形式的调用。
一个喜欢正常的函数调用,另一个喜欢 std::ostream <<运算符输出。 然后,我为每个日志级别分别定义了几个宏,如下所示:
#ifdef DEBUG
#define LOG_DEBUG( strLogBody ) appendLog( leon_log::LogLevel_e::ellDebug, std::string( __func__ ) + "()," + ( strLogBody ) )
#define LOG_INFOR( strLogBody ) appendLog( leon_log::LogLevel_e::ellInfor, std::string( __func__ ) + "()," + ( strLogBody ) )
#define log_debug ( Logger_t( LogLevel_e::ellDebug ) << __func__ << "()," )
#define log_infor ( Logger_t( LogLevel_e::ellInfor ) << __func__ << "()," )
//...more for other log-levels
#else
#define LOG_DEBUG( strLogBody )
#define LOG_INFOR( strLogBody ) appendLog( leon_log::LogLevel_e::ellInfor, ( strLogBody ) )
#define log_debug ( Logger_t( LogLevel_e::ellDebug ) )
#define log_infor ( Logger_t( LogLevel_e::ellInfor ) )
//...more for other log-levels
#endif
当客户端代码空间中定义了"DEBUG"宏时,两者都会形成用于调试目的的产品目标代码。 当没有定义"DEBUG"宏时,前一种形式(如函数调用(不会产生任何二进制代码来加速我的应用程序(如我所愿(,而后者无论如何都会形成产品代码。
有没有办法,我可以绕过那些"<<"调用,就像绕过那些正常的函数调用一样?
到目前为止,我正在使用与@Botje给出的解决方案类似的解决方案。区别在于,矿山是Logger_t的朋友函件,而Botje是会员函件。 以下是我的:
template <typename T>
inline Logger_t& operator<<( Logger_t& lgr, const T& body ) {
if ( lgr.m_LogLevel >= g_ellLogLevel )
dynamic_cast<std::ostringstream&>( lgr ) << body;
return lgr;
};
但我想GCC仍然提供调用二进制代码的函数,即使这些都是"no-op"调用。我不知道如何拆卸我的目标程序,所以我无法确认。
谢谢!请原谅我丑陋的英语!
为什么不让operator<<
在非调试版本中成为无操作:
#ifndef DEBUG
struct Logger_t {
template <class T>
Logger_t& operator <<(const T& o) { return *this; }
};
#endif
编译器应该能够将整个log_debug << ... << ...
链减少到零。
如果还想避免在<<链中调用函数,请operator bool
为Logger_t
和
#define log_debug false && Logger_t{}
相关文章:
- 请解释这句话(cout<<1+int((a<b)^((b-a)&1) )<<endl
- 呼叫运营商<<临时
- 如何防止clang格式在流运算符调用之间添加换行符<<
- <<操作员在下面的行中工作
- 如何将不同的可执行文件合并到一个窗口框架中进行编码?像浏览器一样
- 为什么在C++中对链表这样做?(像堆叠一样处理它们)
- 堆栈和队列是否像C++中的数组一样传递?
- 是否有技术原因阻止 Java 中的 final C++ 像 const 一样严格?
- 访问数据成员(本身是对象)的数据成员,就好像它们是类成员一样
- 我们可以将集合的值存储在变量中吗?就像我们可以将数组的值存储在变量中一样
- 我如何在C++像在 Python 中一样实现 f 字符串?
- 自制的上衣:看起来一样,但不完全相同
- 如何使用 redis-plus-plus 存储二进制数据,就像我想存储结构一样?@for_stack?
- 如何像在 C++ 中处理数组一样对 .txt 文件中的字符进行寻址?
- 如何将两个字符串加在一起,就好像它们是变量一样?
- 像 CPP 中的控制台一样的应用程序
- 为什么C++中没有常量引用,就像常量指针一样?
- 为什么将两个对象分配给另一个对象后,两个对象不一样?
- 有没有像给定的一样的 std::optional_function
- Java 是否像C++模板一样具有泛型推论?