我正在尝试弄清楚如何编写一个将变量值附加到字符串的宏。这是一段无效代码,但我展示它是为了解释我想做什么
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
#define DATA_RESPONCE_0 23
#define DATA_RESPONCE_1 24
#define DATA_RESPONCE_2 25
#define DATA_RESPONCE_3 26
#define my_macro(x) DATA_RESPONCE_##x
int main() {
int i = 0;
int k;
k = my_macro (i);
cout << k;
return 0;
}
在这种情况下,宏被扩展为 DATA_RESPONCE_i,但我希望它是 DATA_RESPONCE_0,这样 23 应该被打印为 k 的值。
最佳答案
你不能用宏来做。预处理(展开宏时)是编译的第一步。早在 i
的值可能已知之前。
如果您打算将运行时值映射到某物,请使用适当的函数:
int my_function(int x)
{
static const int map[] = {
DATA_RESPONCE_0,
DATA_RESPONCE_1,
DATA_RESPONCE_2,
DATA_RESPONCE_3
};
assert (x >= 0 && x < sizeof(map)/sizeof(map[0]));
return map[x];
}
我使用了 assert
宏,因为当 x
不是有效值时您似乎想要硬失败。
关于一个密切相关的话题。除非您的宏位于 C 和 C++ 代码都包含的 header 中,否则更喜欢定义常量的 C++ 样式:
enum class data_response { // Properly scoped.
type_0 = 23,
type_1, // Consecutive values are used after 23. No need to specify 24
type_2,
type_3
};
范围适当的 enum class
将减少对全局命名空间的污染量。甚至可以进一步命名空间本身。它优于不能用于尊重 namespace 或范围的宏。
data_response my_function(int x)
{
static const data_response map[] = {
data_response::type_0,
data_response::type_1,
data_response::type_2,
data_response::type_3
};
assert (x >= 0 && x < sizeof(map)/sizeof(map[0]));
return map[x];
}
关于c++ - 将字符串与变量连接起来并将其视为 C/C++ 中的宏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41479911/