使用预处理器取消std :: cout代码行 [英] Cancelling std::cout code lines using preprocessor
问题描述
可以使用 #define printf
删除对 printf()
的所有调用。如果我有很多调试打印如 std :: cout<< x < endl;
?如何使用预处理程序快速关闭单个文件中的 cout
One can remove all calls to printf()
using #define printf
. What if I have a lot of debug prints like std::cout << x << endl;
? How can I quickly switch off cout <<
statements in a single file using preprocessor?
推荐答案
如果你正在寻找快速删除调试语句的东西,NullStream可以是一个很好的解决方案。但是,我建议创建自己的调试类,当需要更多的调试功能时,可以根据需要进行扩展:
NullStream can be a good solution if you are looking for something quick that removes debug statements. However I would recommend creating your own class for debugging, that can be expanded as needed when more debug functionality is required:
class MyDebug
{
std::ostream & stream;
public:
MyDebug(std::ostream & s) : stream(s) {}
#ifdef NDEBUG
template<typename T>
MyDebug & operator<<(T& item)
{
stream << item;
return *this;
}
#else
template<typename T>
MyDebug & operator<<(T&)
{
return *this;
}
#endif
};
这是一个简单的设置,可以做你最初想要的,您添加了调试级别等功能。
This is a simple setup that can do what you want initially, plus it has the added benefit of letting you add functionality such as debug levels etc..
更新:
现在由于操纵器被实现为函数,如果你想接受操纵器(endl)你可以添加:
Update: Now since manipulators are implemented as functions, if you want to accept manipulators as well (endl) you can add:
MyDebug & operator<<(std::ostream & (*pf)(std::ostream&))
{
stream << pf;
return *this;
}
并且对于所有的机械手类型所有机械手类型):
And for all manipulator types (So that you don't have to overload for all manipulator types):
template<typename R, typename P>
MyDebug & operator<<(R & (*pf)(P &))
{
stream << pf;
return *this;
}
注意这最后一个,因为它也接受常规函数指针。
Be careful with this last one, because that will also accept regular functions pointers.
这篇关于使用预处理器取消std :: cout代码行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!