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

如何将函数模板作为模板参数传递给函数模板?

问题:将函数模板作为模板参数传递给通用循环模板

我现在有如下代码:

#include <cstdint>
#include <iostream>

template<std::uint32_t idx>
void f() {
    std::cout << "f(" << idx << ")\n";
}

template<std::uint32_t n>
void loop1() {
    f<n>();
    if constexpr (n > 0) {
        loop1<n - 1>();
    }
}

template<std::uint32_t idx>
void g() {
    std::cout << "g(" << idx << ")\n";
}

template<std::uint32_t n>
void loop2() {
    g<n>();
    if constexpr (n > 0) {
        loop2<n - 1>();
    }
}

int main() {
    loop1<4>();
    loop2<2>();
}

其中f、g、loop1和loop2必须为函数模板。现在我需要添加更多类似的函数,但loop1和loop2的递归模板循环逻辑完全相同,不想重复编写。

我希望能把函数模板作为模板参数传递给一个通用的loop模板,实现类似如下的效果(以下为示意写法,存在语法错误):

编译时传递的示意代码

#include <cstdint>
#include <iostream>

template<std::uint32_t idx>
void f() {
    std::cout << "f(" << idx << ")\n";
}

template<std::uint32_t idx>
void g() {
    std::cout << "g(" << idx << ")\n";
}

template<std::uint32_t n, typename h>
void loop() {
    h<n>();
    if constexpr (n > 0) {
        loop<n - 1, h>();
    }
}

int main() {
    loop<4, f>();
    loop<2, g>();
}

运行时传递的示意代码1

#include <cstdint>
#include <iostream>

template<std::uint32_t idx>
void f() {
    std::cout << "f(" << idx << ")\n";
}

template<std::uint32_t idx>
void g() {
    std::cout << "g(" << idx << ")\n";
}

template<std::uint32_t n, typename T>
void loop(T h) {
    h<n>();
    if constexpr (n > 0) {
        loop<n - 1>(h);
    }
}

int main() {
    loop<4>(f);
    loop<2>(g);
}

运行时传递的示意代码2

#include <cstdint>
#include <iostream>

template<std::uint32_t idx>
void f() {
    std::cout << "f(" << idx << ")\n";
}

template<std::uint32_t idx>
void g() {
    std::cout << "g(" << idx << ")\n";
}

template<std::uint32_t n, template<std::uint32_t> typename F>
void loop(F h) {
    h<n>();
    if constexpr (n > 0) {
        loop<n - 1>(h);
    }
}

int main() {
    loop<4>(f);
    loop<2>(g);
}

请问这样的需求是否可行?我知道以上示意写法都存在语法错误,只是用来表达我的需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 01:55:16