如何基于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
相关产品推荐
相关产品推荐

