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

如何基于using-directives实现C++模板元编程的递归?

解决C++模板别名递归乘法的问题

你的递归模板别名无法工作的核心原因是:C++标准禁止模板别名直接递归引用自身。模板别名本质是类型的别名,编译器在展开别名时会陷入无限递归,无法完成推导。要实现可变参数的递归乘法,需要借助类模板作为递归的载体,再用模板别名封装简化使用。

修正后的实现代码

#include <iostream>

template< int value_ > struct int_type { 
    static constexpr int value = value_; 
    operator int() { return value; } 
};

template< class lhs, class rhs > using times2 = int_type< lhs::value * rhs::value >;

// 递归实现的类模板
template<class... Args> struct times_impl;

// 终止条件:单个参数,直接返回该类型
template<class T> struct times_impl<T> {
    using type = T;
};

// 递归情况:将第一个参数与剩余参数的乘积结果相乘
template<class First, class... Rest> struct times_impl<First, Rest...> {
    using type = times2<First, typename times_impl<Rest...>::type>;
};

// 用模板别名封装,保持原有的使用方式
template<class... Args> using times = typename times_impl<Args...>::type;

// 测试代码
int main() {
    using i5 = int_type<5>;
    using i3 = int_type<3>;
    using i2 = int_type<2>;
    
    using result = times<i5, i3, i2>; // 5*3*2=30
    std::cout << result{} << std::endl; // 输出30
    
    using single = times<i5>; // 单个参数,返回自身
    std::cout << single{} << std::endl; // 输出5
}

关键说明

  • 类模板递归:类模板times_impl支持可变参数,通过偏特化实现递归终止条件(单个参数时直接返回该类型),递归时将第一个参数与剩余参数的乘积结果结合。
  • 模板别名封装:times模板别名通过typename times_impl<Args...>::type获取最终类型,保持了原代码中想要的简洁调用方式。
  • 兼容性:该实现符合C11及以上标准,因为可变参数模板和模板别名都是C11引入的特性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 04:33:43