首页 > 解决方案 > 带参数的 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一样。

标签: c++qtmacros

解决方案


#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

推荐阅读