如何在 C++中实现这个效果?

104 天前
 sbldehanhan
#ifdef DEBUG
#define dprintf(x...)	printf(x)
#else
#define dprintf(x...)
#endif

如上。上面的这个是用的 printf 函数,在 C++中用有什么负面影响吗?不是说 cout 和 printf 最好不要混用吗?所以,能不能将上面的逻辑用 cout 实现?

1905 次点击
所在节点    C++
6 条回复
AFOX
104 天前
用 spdlog 库
Astor
104 天前
C++ 用 printf 没问题啊,甚至性能可能稍微好一点。不过日志打印到 stderr 里面。
kirory
104 天前
class DummyStream{
public:
template<typename T>
DummyStream operator << (const T&) const {
return * this;
}
};


#ifdef DEBUG
#define dprintf(x...) std::cout
#else
#define dprintf(x...) DummyStream{}
#endif
kkk9
104 天前
cpp 要站在巨人的肩膀上,所以 #1 SPDLOG 推荐
sjkdsfkkfd
104 天前
用 fmt 多好,20 自带,20 之前用 libfmt

```
#ifdef DEBUG
#define dprintf(...) fmt::print(__VA_ARGS__)
#else
#define dprintf(...) static_assert(true,"")
#endif
```
setname
104 天前
```
#define dprintf(x...) do { \
int size_s = std::snprintf(nullptr, 0, x) + 1; \
char* str = new char[size_s]; \
std::snprintf(str, size_s, x); \
cout << str << endl; \
delete []str; \
} while(0)
```

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/1012510

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX