c++ - 带参数的 C++ 宏
问题描述
我想这样定义:
#define log(x) \
#if (x) \
cout << "\n" << x \
#else \
cout \
例子:
log() << abc
~
cout << abc
和
log(name) << abc
~
cout << "\n" << name << abc
它类似于这里的问题中的问题C preprocessor macro specialization based on an argument
我想使用define,因为实际上,我使用cout是因为人们可以很容易地理解我的意图。
我做 Qt 并且需要使用 QLoggingCategory 记录
QLoggingCategory category("MyNameSpace");
当需要日志时,我需要使用语法
qCDebug(category) << something_need_log
在这里,qCDebug(category)就像我的问题中的cout一样。
解决方案
#include <iostream>
std::ostream& log() {
return std::cout;
}
std::ostream& log(const std::string& x) {
return std::cout << "\n" << x;
}
int main() {
log() << "message"; // std::cout << "message";
log("name: ") << "message"; // cout << "\n" << "name: " << message;
return 0;
}
输出:
message
name: message
推荐阅读
- logback - logback如何将日志文件存储在名称为当前日期的文件夹中
- syntax - 这个操作符`=>`在verilog中是什么意思
- google-apps-script - 如果输入重复,则覆盖 Google 表格(用于表单响应)行
- sql-server-2012 - SQL Server 2012 - 为什么更改兼容模式会影响查询中的并行性?
- java - Arrays.asList(word.toCharArray()) 不返回列表?
- artifactory - 在 pypi repos 上推送复制
- react-native - 有没有办法在 React Native 中全局设置字体?
- java - 集成测试 Given/When/The Java
- qt - NMAKE 静态链接错误
- python-2.7 - 使用 Appium 和 Python 在多个设备上并行运行