我有一个用 C++ 编写的日志系统,上面写有这种类型的函数:
void processMessages();
void DEBUG_MSG(const std::string& appender,const char* msg, ...);
void INFO_MSG(const std::string& appender,const char* msg, ...);
void WARNING_MSG(const std::string& appender, const char* msg, ...);
void ERROR_MSG(const std::string& appender, const char* msg, ...);
void FATAL_MSG(const std::string& appender, const char* msg, ...);
我想在 C++ 中通过宏禁用。 我读过这个帖子:Disable functions using MACROS但是
#ifdef GLOG_SILENCE
#define processMessages (void)sizeof
#define DEBUG_MSG (void)sizeof
#define INFO_MSG (void)sizeof
#define WARNING_MSG (void)sizeof
#define ERROR_MSG (void)sizeof
#define FATAL_MSG (void)sizeof
#else //GLOG_SILENCE
void processMessages();
void DEBUG_MSG(const std::string& appender,const char* msg, ...);
void INFO_MSG(const std::string& appender,const char* msg, ...);
void WARNING_MSG(const std::string& appender, const char* msg, ...);
void ERROR_MSG(const std::string& appender, const char* msg, ...);
void FATAL_MSG(const std::string& appender, const char* msg, ...);
#endif //GLOG_SILENCE
无法正常工作。我不断收到如下错误:
In file included from ../src/test_core.cpp:2:
../src/test_Log.h: In member function ‘virtual void LogTestFixtureTest_defining_SILENCE_macro_avoids_write_and_processing_activity_from_log_Test::TestBody()’: ../src/test_Log.h:63: error: expected unqualified-id before ‘(’ token ../src/test_Log.h:63: error: expected primary-expression before ‘void’ ../src/test_Log.h:63: error: expected ‘;’ before ‘sizeof’ ../src/test_Log.h:64: error: expected unqualified-id before ‘(’ token ../src/test_Log.h:64: error: expected primary-expression before ‘void’ ../src/test_Log.h:64: error: expected ‘;’ before ‘sizeof’
我怀疑这个问题与Log是一个类有关,但我不知道该怎么做。 一些帮助?
最佳答案
确实,如果这些是成员函数,那么“静默”版本将扩展为无意义:
log.(void)sizeof(stuff);
您可以定义一个什么都不做的成员函数,以及包含其参数的宏:
void nothing() {}
#define processMessages(...) nothing()
然后使用“静默”版本将提供有效的代码,这些代码应该编译为空:
log.nothing();
这样做的缺点是 (a) 您依赖编译器内联空函数,而不是生成函数调用; (b) 在静默模式下编译时不检查参数的语法。
关于c++ - 使用预处理器宏取消定义函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10226151/