c++ - 将字符串与变量连接起来并将其视为 C/C++ 中的宏

标签 c++ c++11

我正在尝试弄清楚如何编写一个将变量值附加到字符串的宏。这是一段无效代码,但我展示它是为了解释我想做什么

#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/

相关文章:

c++ - 使用 BOOST_FOREACH 时如何测试 vector 中的最后一个元素?

c++ - Visual Studio 2010转换2005解决方案(C++项目)丢失项目依赖

c++ - 在Leetcode上提交解决方案时出现堆栈缓冲区溢出错误

c++ - 当我使用自定义分配器溢出 vector 时,为什么没有出现段错误?

c++ - 编译时间间隔检查器

c++ - 如何让 Coverity 静态分析兼容 C++0x 标准?

c++ - 在调试器中显示 ifstream 的当前文件夹

c++ - 哪个类负责序列化?

c++ - 将 vector 作为值分配给 std::unordered_map 中的键

c++ - MSVC 2012 通过 SFINAE 检测模板函数的模板参数数量