c++ - 管理字符串文字的最佳实践
问题描述
在一个文件中管理字符串而不是多次写出它们的最佳实践是什么?我的想法是创建一个简单的 string_library.h 文件,其中包含映射中的所有字符串并方便地定义以获取名称和 ID。像这样的东西:
#include <string>
#include <map>
#define SENSOR1_ID 0
#define SENSOR2_ID 1
#define SENSOR1_NAME string_library[SENSOR1_ID]
#define SENSOR2_NAME string_library[SENSOR2_ID]
std::map<unsigned int, const std::string> string_library{
std::make_pair(SENSOR1_ID, "Sensor1 Name"),
std::make_pair(SENSOR2_ID, "Sensor2 HI Name")
};
这样,字符串只需写出一次,并且可以通过定义或从地图中轻松获取。该地图可能对能够迭代地图很有用,但也许其他一些结构更有意义。
解决方案
您可以简单地使用一个constexpr
变量:
constexpr auto SENSOR1_NAME = "Sensor1 Name";
不需要宏,也不需要昂贵的动态内存开销。
推荐阅读
- javascript - Vue.js - 组件模板不使用 v-for 渲染
- python - 如何将图像添加到 Python 的 icalendar 中的事件?
- puppet - 用于安装和运行 apache2 或 httpd 的平台无关清单
- java - 非法的表达开始
- node.js - Express API 在我的 GET all 请求中返回不需要的“数据”部分
- typo3 - LTS 7 中“上边距”和“下边距”的 TYPO3 替换
- php - WP post__not_in 另一个查询不过滤
- google-cloud-firestore - Cloud Firestore:在不知道字段名称的情况下检查值是否存在
- postgresql - Postgresql 11.1:“运行安装后步骤时出现问题。安装可能无法正确完成。配置或权限错误。”
- php - 在免费 000webhsot 上上传我的 laravel 项目后,用户部分正在工作,但管理部分给出此错误 1->“未找到查看 [admin\includes\app]”