sujin
sujin

Reputation: 2853

Macro to add character at end of string without passing source string

I am trying to write a macro which add a char (end function key) at end of the string without passing source string.

Statement:

LEVEL_ENTRY(level) << "Level1 Message";

Expected macro expansion

LEVEL_ENTRY(level) levelParser(level, std::ostringstream().flush() << "Level1 Message");

I am trying like this

#define LEVEL_ENTRY(level) levelParser(level, std::ostringstream().flush()

Is this kind of expansion (without passing args) possible with C++ macro?

EDIT

To make it work currently I am doing like

#define LEVEL_ENTRY(level, msg) levelParser(level, std::ostringstream().flush() << msg)

LEVEL_ENTRY(level, "Level1 Message"<< "Message2");

Real problem for this is I can't simply change the statement now' it is used in more than 1000 places in the project.

Upvotes: 0

Views: 248

Answers (3)

M.M
M.M

Reputation: 141574

One way to solve your problem would be:

struct Foo { int level; };

auto operator<<(Foo foo, char const *s)
{ 
    return levelParser(foo.level, std::ostringstream().flush() << s);
}

#define LEVEL_ENTRY(level) Foo{level}

Upvotes: 2

Bill Lynch
Bill Lynch

Reputation: 81926

Sure, but there's no macro involved:

class LEVEL_ENTRY {
    public:
        LEVEL_ENTRY(level): level_(level) {}
        LEVEL_ENTRY(LEVEL_ENTRY const &) = delete;
        LEVEL_ENTRY & operator=(LEVEL_ENTRY const &) = delete;

        ~LEVEL_ENTRY() {
             levelParser(level, oss);
        }

        LEVEL_ENTRY & operator<<(const char *message) {
             oss << message;
        }

    private:
        int level_;
        std::ostringstream oss;
};

LEVEL_ENTRY(1) << "Level1 Message";

Upvotes: 2

kfsone
kfsone

Reputation: 24249

No, you can't << things to a macro. Macros are handled by the pre-processor and are not seen by the C++ language parser, and macros do not support any kind of << syntax.

A macro is a fragment of code which has been given a name. Whenever the name is used, it is replaced by the contents of the macro. There are two kinds of macros. They differ mostly in what they look like when they are used. Object-like macros resemble data objects when used, function-like macros resemble function calls.

https://gcc.gnu.org/onlinedocs/cpp/Macros.html

Upvotes: 3

Related Questions