简体   繁体   English

C ++宏和重载

[英]C++ Macros and overloading

I am working with c++ Macros, trying to implement on certain pattern. 我正在使用c ++宏,试图以某些模式实现。 I have the following 3 macros: 我有以下3个宏:

#define First Objct t; t
#define Second a() / b()
#define Third ;

I've overload the lambda-ops in format: Objct [ Objct ] 我以以下格式过载了lambda-ops: Objct [ Objct ]

So when I have in main() a line like: 所以当我在main()中有一行像:

First [ Second ] Third

it works fine, as it's 'translated' into: 它工作正常,因为它已“翻译”为:

Objct t; t[a()/b()]

(note: a() and b() are dummy functions returning type object.) (注意: a()b()是返回类型对象的伪函数。)

The hard part, is that I also have to make it work without the lambdas. 困难的是,我还必须使它在没有lambda的情况下工作。

First Second Third

which means 意思是

Objct t; t a() / b()

In that case, I got a semicolon missing from FIRST to SECOND . 在这种情况下,我从FIRSTSECOND缺少了分号。 I'm trying to figure out, what changes could be made (probably) to FIRST macro so it can compile in both cases. 我试图弄清楚,可以对FIRST宏进行哪些更改(可能),以便可以在两种情况下进行编译。 I'm not sure if I managed to explain myself properly. 我不确定我是否能够正确地解释自己。 Any ideas? 有任何想法吗?

Your question in pretty strange. 您的问题很奇怪。 I would strongly advise you not to use such a weird construct in real code. 我强烈建议您不要在实际代码中使用这种怪异的构造。 But I've looked at your question as if it were a funny puzzle. 但是我看着你的问题好像是一个有趣的难题。

Potential solution 潜在解决方案

I think there is no way to make both statement compile by changing only First . 我认为没有办法通过仅更改First来使两个语句都编译。 But if you change Second to: 但是,如果将Second更改为:

#define Second +0,a() / b()

it compiles in both cases, under the sole condition that operator + is defined for Objct in combination with an int . 它在两种情况下都可以编译,唯一的条件是结合intObjct定义了operator + If you manage to implement this operator without side effect, it would even produce what you expect. 如果您设法实现该运算符而没有副作用,那么它甚至会产生您期望的结果。

Live demo 现场演示

Why does it work ? 为什么行得通?

This definition makes use of the coma operator, the only issue being that the coma operator requires two expressions. 该定义使用了逗号运算符,唯一的问题是逗号运算符需要两个表达式。 +0 solves the issue syntactically, as +0 alone is valid, and t+0 is valid with the above-mentionned requirement. +0从句法上解决了这个问题,因为仅+0有效,而t+0在上述要求下有效。

With such a definition, First Second Third is preprocessed as 有了这样的定义, First Second Third被预处理为

 Objct t; t +0,a() / b() ;     // comma operator evaluates t+0  
                               // then a()/b()

And First [Second] Third would be preprocessed as First [Second] Third将被预处理为

 Objct t; t [+0,a() / b()] ;  // comma operator makes +0 being evaluated
                              // and lost and [] is called with value of a()/b(). 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM