宏参数顺序很重要
Macros argument order matters?
当我编译下面的程序时,编译器产生错误。
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;
}
而下面的程序可以正确编译
#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;
}
为什么宏体中的参数顺序很重要?
尝试去掉+
来连接字符数组字面量:
#define JMP(add) "DEFAULT is : " DEFAULT " JMP is : " add
注意:由于add
将从您的样本扩展到std::string
值(to_string(10)
),因此这也不起作用。您需要像这样调用宏:
cout << JMP("10") << endl;
另一种解决方案是使部件成为std::string
实例:
#define JMP(add) std::string("DEFAULT is : " DEFAULT " JMP is : ") + add
该错误告诉您,给定给二进制表达式的操作数(即+ operator
)不是预期的类型。该操作符至少有一个操作数需要const string &
(或者使用c++ 11时需要string &
)。加上从左到右的求值就是当你改变顺序时它能工作的原因。
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
如果您有一个const string &
作为启动器*,您可以整天保持连接const char *
s:
cout << "JUMP is : " + to_string(10) + " DEFAULT is : " + "00000" + "game is " + "concentration, " + "category is " + "..." << endl;
所以,这实际上与宏参数的顺序无关,而是与字符串、char指针、连接、结合性和操作符有关。
*在体育比赛中
相关文章:
- 函数调用中参数的顺序重要吗
- C++部分概念 id:显式模板规范顺序/第一个参数的特殊状态的原因是什么?
- lambda 作为接受其他参数的参数的初始化顺序
- 运算符 new 的执行顺序和构造函数的参数
- 如何检查参数包是否具有执行顺序中的确切类型
- std::bind() 参数列表中函子的执行顺序(可能与函数参数的求值顺序无关)
- 构造函数中没有参数的对象类成员按什么顺序初始化?
- 如何实现对参数顺序不可知的std::same_as的广义形式(即对于两个以上的类型参数)
- 用作成员构造函数参数的函数的求值顺序
- C++17的可选和可变顺序函数参数
- 委派的 ctor 是否受参数计算顺序的影响?
- x64 函数调用参数推送/移动顺序 (MSVC)
- 函数参数计算顺序与 Lambda 捕获评估顺序
- 反转模板(整数)参数的顺序
- 大括号和括号之间的参数计算顺序
- 约束模板参数顺序的更简单方法
- C++ 更改基于参数设置的默认顺序
- 重载运算符以允许C++中参数的不同顺序
- 正确对齐内存模板,参数顺序不变
- 为具有默认值的非顺序参数函数创建启动器