关于C#:宏在字符串末尾添加字符而不传递源字符串

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

我正在尝试编写一个宏,它在字符串末尾添加一个字符(结束功能键)而不传递源字符串。

声明:

1
LEVEL_ENTRY(level) <<"Level1 Message";

预期的宏扩展

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

我正在尝试这样

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

C 宏可以进行这种扩展(不传递参数)吗?

编辑

为了让它现在能正常工作,我正在做类似的事情

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

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

真正的问题是我现在不能简单地更改语句'它在项目中的 1000 多个地方使用。


不,你不能将 << 东西放到宏中。宏由预处理器处理,C 语言解析器看不到,宏不支持任何类型的 << 语法。

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


解决问题的一种方法是:

1
2
3
4
5
6
7
8
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}


当然可以,但不涉及宏:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
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";