带参数的C ++宏

时间:2019-08-22 02:05:20

标签: c++ qt macros

我想这样定义:

    #define log(x)          \
    #if (x)                 \
        cout << "\n" << x   \
    #else                   \  
        cout                \

示例:

    log() << abc 
    ~
    cout << abc

    log(name) << abc
    ~
    cout << "\n" << name << abc

与这里C preprocessor macro specialisation based on an argument

中的问题类似

我想使用 定义 ,因为实际上,我使用 cout 以便人们可以轻松理解我的意图。

我正在做Qt,需要使用QLoggingCategory记录日志

    QLoggingCategory category("MyNameSpace");

当需要登录时,我需要使用语法

    qCDebug(category) << something_need_log

在这里, qCDebug(类别) 就像我的问题中的 cout

1 个答案:

答案 0 :(得分:2)

#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