[英]Macros argument order matters?
When i compile the below program following error is generated by the compiler.当我编译以下程序时,编译器会生成以下错误。
example.cpp:12:13: error: invalid operands to binary expression ('const char *' and 'const char *')
cout << JMP(to_string(10)) << endl;
^~~~~~~~~~~~~~~~~~
example.cpp:6:34: note: expanded from macro 'JMP'
#define JMP(add) "DEFAULT is : " + DEFAULT + " JMP is : " + add
~~~~~~~~~~~~~~~ ^ ~~~~~~~
#include <iostream>
#include <string>
#define DEFAULT "00000"
#define JMP(add) "DEFAULT is : " + DEFAULT + " JMP is : " + add
using namespace std;
int main()
{
cout << JMP(to_string(10)) << endl;
return 0;
}
Whereas the below program compiles properly而下面的程序编译正确
#include <iostream>
#include <string>
#define DEFAULT "00000"
#define JMP(add) "JMP is : " + add + "DEFAULT is : " + DEFAULT
using namespace std;
int main()
{
cout << JMP(to_string(10)) << endl;
return 0;
}
Why the order of argument present in the macro body matters ?为什么宏体中的参数顺序很重要?
Try to get rid of the +
to concatenate char array literals:尝试去掉+
来连接字符数组文字:
#define JMP(add) "DEFAULT is : " DEFAULT " JMP is : " add
NOTE: Since add
will expand to a std::string
value ( to_string(10)
) from your sample, this won't work either.注意:由于add
将从您的示例中扩展为std::string
值( to_string(10)
),因此这也不起作用。 You'll need to call the macro like this:您需要像这样调用宏:
cout << JMP("10") << endl;
An alternate solution would be making the parts std::string
instances:另一种解决方案是制作部分std::string
实例:
#define JMP(add) std::string("DEFAULT is : " DEFAULT " JMP is : ") + add
The error is telling you that the operands given to the binary expression (ie + operator
) are not of expected types.该错误告诉您赋予二进制表达式(即+ operator
)的操作数不是预期的类型。 This operator is expecting a const string &
(or a string &
using C++ 11) for at least one of its operands.该运算符需要至少一个操作数的const string &
(或使用 C++ 11 的string &
)。 That plus left to right evaluation is why it works when you switch the order.加上从左到右的评估,这就是当您切换顺序时它起作用的原因。
cout << to_string(10) + " is the JUMP" << endl; // having valid operands, + operator returns a string object
cout << "JUMP is : " + to_string(10) << endl; // same here
cout << "DEFAULT is : " + "00000" << endl; // no bueno: both operands are const char pointers
Provided that you have a const string &
as a starter* , you can keep concatenating const char *
s all day long:假设你有一个const string &
作为starter* ,你可以整天连接const char *
s:
cout << "JUMP is : " + to_string(10) + " DEFAULT is : " + "00000" + "game is " + "concentration, " + "category is " + "..." << endl;
So, this actually is not about order of macro arguments but about strings, char pointers, concatenation, associativity, and operators.所以,这实际上不是关于宏参数的顺序,而是关于字符串、字符指针、连接、结合性和运算符。
*as in a sports game. *就像在体育比赛中一样。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.