首页 > 解决方案 > 管理字符串文字的最佳实践

问题描述

在一个文件中管理字符串而不是多次写出它们的最佳实践是什么?我的想法是创建一个简单的 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")
};

这样,字符串只需写出一次,并且可以通过定义或从地图中轻松获取。该地图可能对能够迭代地图很有用,但也许其他一些结构更有意义。

标签: c++stringconstants

解决方案


您可以简单地使用一个constexpr变量:

constexpr auto SENSOR1_NAME = "Sensor1 Name";

不需要宏,也不需要昂贵的动态内存开销。


推荐阅读