如何在编译期将std::vector转为std::array且避免重复计算?
解决方案
核心问题在于你没有将存储计算结果的vec声明为constexpr auto——仅用const修饰的变量无法提供编译期常量值作为std::array的模板参数,而C++20及以后版本支持constexpr std::vector,只要修正这一点就能避免重复调用make_vector。
修改后的代码
constexpr auto make_vector() { // 复杂计算逻辑 return std::vector{1, 2, 3}; } constexpr auto make_array() { constexpr auto vec = make_vector(); // 将const改为constexpr std::array<int, vec.size()> result{}; std::copy(vec.cbegin(), vec.cend(), result.begin()); return result; } int main() { constexpr auto result = make_array(); // std::array<int, 3>{1, 2, 3} }
原理说明
make_vector是constexpr函数,在constexpr上下文中调用它初始化constexpr变量vec时,所有计算会在编译期完成。vec.size()此时是编译期常量,完全符合std::array对模板参数的要求,因此可以直接用来指定数组大小。- 整个过程仅调用一次
make_vector,既保证了编译期计算,又避免了冗余操作。
通用化扩展(支持任意类型)
如果需要适配更多类型的容器计算,可以封装一个通用转换函数:
template<typename T> constexpr auto vector_to_array(const std::vector<T>& vec) { std::array<T, vec.size()> arr{}; std::copy(vec.begin(), vec.end(), arr.begin()); return arr; } constexpr auto make_array() { constexpr auto vec = make_vector(); return vector_to_array(vec); }
内容的提问来源于stack exchange,提问作者fdan
相关产品推荐
相关产品推荐

