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

C++17中将constexpr array元素展开为模板参数实现编译期调用

问题原因

你的代码存在3个核心错误:

  • 你传入的lambda需要将数组元素作为模板参数调用,但原实现中invoke_param是把元素作为普通函数参数传递给可调用对象,和lambda的调用规则不匹配
  • main函数存在笔误:定义的lambda变量名为fun,调用时写的是func
  • 模板化调用可调用对象时,缺少.template标识告知编译器后续尖括号为模板参数列表,会导致编译期语法解析错误

修正后完整代码

#include <array>
#include <utility>
#include <cstddef>

template <auto param, typename Function, typename... Args>
void invoke_param(Function func, Args&&... args)
{
    // 将元素作为模板参数传入可调用对象
    func.template operator()<param>(std::forward<Args>(args)...);
}

template <auto... params, typename Function, typename... Args>
void invoke_params(Function func, Args&&... args)
{
    (invoke_param<params>(func, std::forward<Args>(args)...), ...);
}

template <auto& Array, std::size_t... Indices, typename Function, typename... Args>
void for_each_array_impl(std::index_sequence<Indices...>, Function func, Args&&... args)
{
    invoke_params<Array[Indices]...>(func, std::forward<Args>(args)...);
}

template <auto& Array, typename Function, typename... Args>
void for_each_array(Function func, Args&&... args)
{
    for_each_array_impl<Array>(
        std::make_index_sequence<std::size(Array)>(), func, std::forward<Args>(args)...);
}

static constexpr std::array<int, 5> ARR{1,2,3,4,5};
int main() {
    auto fun = []<int E>() {
        static_assert(E > 0);
        // 自定义业务逻辑
    };
    // 修正变量名笔误
    for_each_array<ARR>(fun);
}

改动说明

  • 调整invoke_param的调用逻辑,用.template operator()<param>的形式将数组元素作为模板参数传入可调用对象,匹配你定义的模板lambda的调用规则
  • 增加了完美转发逻辑,避免参数拷贝开销,不影响核心功能可忽略
  • 修正变量名笔误
  • 明确了函数返回值为void,避免返回类型推导的潜在问题

内容的提问来源于stack exchange,提问作者fluter

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 21:09:03