You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将任意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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 17:00:11