如何模拟指定初始化器创建枚举索引数组?
结论
标准 C++ 不能直接照搬 [bitbucket] = "https://bitbucket.org/.*" 这种数组下标形式的 designated initializer。C++20 的 designated initializers 只适用于聚合体成员,不能按数组下标指定元素;在 C++ 模式下,GCC/Clang 遇到非平凡元素时也常报 non-trivial designated initializers not supported。要模拟原有逻辑,比较稳妥的做法是在 constexpr 工厂函数里创建 std::array<T, N>,再按枚举的底层值把元素写入对应位置,没写到的元素由 {} 做值初始化。
原因
constexpr std::string_view ServicesNames[] = { [bitbucket] = ... }; 里的 [index] = ... 属于 C 的指定初始化器扩展,不是标准 C++ 语法。即便某些编译器在 C 里支持这种写法,C++ 对 designated initializers 的限制也不一样:必须按聚合体成员的声明顺序指定,不能用于数组下标。std::string_view 又是类类型,所以会报 non-trivial designated initializers not supported。
推荐写法:constexpr 工厂函数
数组长度要覆盖最大的枚举底层值。示例里最大的是 bitbucket == 4,所以长度取 5:
#include <array>
#include <cstddef>
#include <string_view>
#include <utility>
enum Services : std::size_t {
github = 0,
gitlab = 1,
bitbucket = 4,
};
inline constexpr std::size_t ServicesCount =
static_cast<std::size_t>(bitbucket) + 1; // 5
template <class T, std::size_t N, class... Pairs>
constexpr std::array<T, N> make_indexed_array(const Pairs&... pairs) {
std::array<T, N> result{};
((result[static_cast<std::size_t>(pairs.first)] = pairs.second), ...);
return result;
}
constexpr auto ServicesNames = make_indexed_array<std::string_view, ServicesCount>(
std::pair<Services, std::string_view>{github, "https://github.com/.*"},
std::pair<Services, std::string_view>{gitlab, "https://gitlab.com/.*"},
std::pair<Services, std::string_view>{bitbucket, "https://bitbucket.org/.*"}
);
这样 ServicesNames[github]、ServicesNames[gitlab]、ServicesNames[bitbucket] 都能取到预期值,其他没有赋值的元素是空的 std::string_view{}。ServicesNames 是 constexpr,可以用于编译期。
更直接的 lambda 写法
不想写通用 helper 的话,也可以直接写 constexpr lambda:
constexpr auto ServicesNames = [] {
std::array<std::string_view, 5> a{};
a[github] = "https://github.com/.*";
a[gitlab] = "https://gitlab.com/.*";
a[bitbucket] = "https://bitbucket.org/.*";
return a;
}();
这样逻辑更直白,缺点是需要手写数组长度和赋值语句。
注意事项
N必须大于等于最大枚举底层值加 1。枚举值不连续时,不能直接用枚举数量当数组长度。- 如果枚举值可能变化,建议把最大索引单独定义成常量,或者用
std::to_underlying(C++23 起)提高可读性。 - 原问题说枚举值彼此不同;如果实际项目可能出现重复索引,后写入的值会覆盖先写入的值,需要自己加编译期检查。
- 不要把
[index] = ...这种数组指定初始化语法当作可移植的 C++ 方案。
备注:内容仅供参考。
