在我们的代码库中,我们有很多“枚举到字符串”数组,例如 array<pair, string>> 用于从枚举中获取字符串。
这些数组不能是 constexpr,所以我正在考虑从 string 更改为 string_view。但这将导致所有使用此字符串的地方现在从 string_view 转换为字符串,我担心运行时成本。
下面是示例代码(不是真正的代码,所以不用担心名称等):https ://godbolt.org/z/6nEh8s
#include <map>
#include <array>
#include <string>
#include <string_view>
#include <iostream>
enum class Color
{
red, blue, green
};
// Old way
using cp1 = std::pair<Color, std::string>;
const std::array colorStrings1 = {cp1{Color::red, "Red"}, cp1{Color::blue, "Blue"}, cp1{Color::green, "Green"}};
// New way
using cp2 = std::pair<Color, std::string_view>;
constexpr std::array colorStrings2 = {cp2{Color::red, "Red"}, cp2{Color::blue, "Blue"}, cp2{Color::green, "Green"}};
std::string toString1(Color color)
{
for (const auto& [e, s] : colorStrings1) {
if (e == color) {
return s;
}
}
return {};
}
constexpr std::string_view toString2(Color color)
{
for (const auto& [e, s] : colorStrings2) {
if (e == color) {
return s;
}
}
return {};
}
int main()
{
const std::string s1{toString1(Color::red)};
const std::string s2{toString2(Color::blue)};
std::cout << s1 << " " << s2 << std::endl;
return 1;
}
colorStrings2 是在编译时创建的 - 这非常好 - 与在启动期间创建的 colorStrings1 不同。但我担心创建 s2 的成本远大于创建 s1 的成本。
我知道 C++20 最终会得到 constexpr 字符串,然后我就可以像那样将 colorStrings1 从 const 更改为 constexpr (如果我理解正确的话),但这似乎不会在不久的将来.
有人可以在这里给我建议吗?从 colorStrings1 更改为 colorStrings2 是好主意还是坏主意?这部分是为了更深入地了解 c++,因此任何见解都值得赞赏。