-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.

3
  • 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. Commented Aug 22, 2019 at 2: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.) Commented Aug 22, 2019 at 2: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. Commented Aug 22, 2019 at 3:50

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.