如何将任意constexpr函数作为参数传入constexpr数组计算?
问题:将任意constexpr函数传入constexpr数组计算
我在尝试把任意constexpr函数作为参数传入,用来计算constexpr数组时遇到了困难。
非constexpr场景的实现代码
float calcAdd2(float a) { return a + a; } float calcPow2(float a) { return a * a; } template <class Func> auto calcArrArithmetic(int size, Func func) { std::vector<float> result; for (auto i = 0; i < size; i++) { result.emplace_back(func(i)); } return result; }
基础constexpr数组计算尝试
我先实现了基础的constexpr数组计算逻辑,这段代码可以正常运行:
template <std::size_t... I> std::array<float, sizeof...(I)> fillArray(std::index_sequence<I...>) { return std::array<float, sizeof...(I)>{ calcAdd2(I)... }; } template <std::size_t N> std::array<float, N> fillArray() { return fillArray(std::make_index_sequence<N>{}); } static const auto CALC_FIRST_10_ADD2 = fillArray<10>();
目标需求
现在我希望将calcAdd2推广为任意constexpr函数,实现如下形式的调用:
static const auto CALC_FIRST_10_ADD2 = fillArray<10>(calcAdd2); static const auto CALC_FIRST_10_POW2 = fillArray<10>(calcPow2);
补充解决方案
- C++17版本:由madhur4127提供
- C++20版本:由BlackCatHole提供
内容的提问来源于stack exchange,提问作者Vladislav
相关产品推荐
相关产品推荐

