-1

I want to define like this:

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

Example:

    log() << abc 
    ~
    cout << abc

and

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

It similar the problem in the question in here C preprocessor macro specialisation based on an argument

I want to use define because actually, I use cout for people can easily understand my intent.

I doing the Qt and need log using QLoggingCategory

    QLoggingCategory category("MyNameSpace");

And when need log, I need to use the syntax

    qCDebug(category) << something_need_log

Here, qCDebug(category) like the cout in my question.

tackelua
  • 1
  • 1
  • 6
    Sorry, macros don't work this way, and this is not what they're for. This is something that easily done using a very simple template function. – Sam Varshavchik Aug 22 '19 at 02:12
  • 1
    Why do you *want* to use a macro? They tend to cause more problems than the alternatives. (By which I mean they cause problems and the alternatives usually do not.) – JaMiT Aug 22 '19 at 02:15
  • Macros, old style cast, most implicit conversions, etc. are things that C++ has only because deprecating them just breaks to much code, but they should be avoided in new code. – Mirko Aug 22 '19 at 03:50

1 Answers1

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;
}

Output:

message
name: message
273K
  • 29,503
  • 10
  • 41
  • 64
  • Thanks @S.M. but I want to use ***define*** because actually, I use ***cout*** for people can easily understand my intent. I doing the Qt and need log using QLoggingCategory QLoggingCategory category("MyNameSpace"); And when need log, I need to use the syntax qCDebug(LogQuoteButton) << something_need_log Here, ***qCDebug(LogQuoteButton)*** like the ***cout*** in my question. – tackelua Aug 22 '19 at 07:29