如何在常量头文件中声明编译时常量的不同大小列表集合?
统一访问不同大小编译时常量子列表的问题
我在优化应用与常量头文件时,使用inline constexpr常量避免多副本并实现编译时常量。现在需要创建一个父容器,来统一访问多个大小不同的子列表。
最初尝试的方案(不可行)
我原本计划在常量头文件中定义如下编译时常量子列表:
inline constexpr std::array<CONST int, size1> first = { some CONST values }; inline constexpr std::array<CONST int, size2> second= { some other CONST values }; inline constexpr std::array<CONST int, size3> third = { some other CONST values };
并尝试将它们存入父容器CONTAINER parent = { first, second, third };以实现统一访问,但发现由于std::array的模板参数(大小)不同,无法使用通用的指针或容器来存放这些子列表,因此该方案无法实现。
当前使用的方案
我改用了std::vector来定义子列表:
inline const std::vector<int> first = { some CONST values }; inline const std::vector<int> second = { some other CONST values }; inline const std::vector<int> third = { some other CONST values };
再定义父容器为指针数组:
inline constexpr std::array<const std::vector<CONST int>*, 3> parent = {&first, &second, &third};
目前可以通过const std::vector<CONST int>* to_access = parent[0];正常访问子列表,但不确定这个方案是否存在未被发现的问题。
需求
我想了解:
- 当前使用的指针数组方案是否有隐藏的问题?
- 是否存在基于constexpr的替代实现方案(比如constexpr函数、迭代器等),且必须避开仅MSVC支持的C++20 constexpr vector?
内容的提问来源于stack exchange,提问作者Chenoille
相关产品推荐
相关产品推荐

