如何在编译时检查整数数组是否为回文?
编译时检查整数数组是否为回文的实现
我们可以利用C++模板的特化与递归展开特性,实现编译时的整数数组回文判断,完全贴合你给出的框架。
1. 基础模板定义
首先实现用于包裹整数参数包的IntArray空类:
template <int...> class IntArray {};
2. 核心Palindrome模板实现
通过模板特化处理不同长度的数组,递归判断回文逻辑:
// 通用模板声明 template <typename Array> struct Palindrome; // 空数组特化:空数组属于回文 template <> struct Palindrome<IntArray<>> { static constexpr bool check = true; }; // 单元素数组特化:单个元素必然是回文 template <int Value> struct Palindrome<IntArray<Value>> { static constexpr bool check = true; }; // 多元素数组特化:首尾元素相等 + 中间子数组是回文 template <int First, int... Middle, int Last> struct Palindrome<IntArray<First, Middle..., Last>> { static constexpr bool check = (First == Last) && Palindrome<IntArray<Middle...>>::check; };
3. 编译时验证
使用static_assert在编译阶段验证结果:
// 验证回文数组 static_assert(Palindrome<IntArray<1, 2, 1>>::check == true, "1,2,1 应为回文数组"); static_assert(Palindrome<IntArray<1, 3, 10, 3, 1>>::check == true, "1,3,10,3,1 应为回文数组"); // 验证非回文数组 static_assert(Palindrome<IntArray<1, 2, 3>>::check == false, "1,2,3 不应为回文数组"); static_assert(Palindrome<IntArray<5, 4, 3, 2>>::check == false, "5,4,3,2 不应为回文数组");
实现逻辑说明
- 针对空数组、单元素数组这类边界场景,直接通过模板特化返回
true; - 多元素数组的判断逻辑拆分为两步:先校验首尾元素是否相等,再递归判断中间的子数组是否为回文;
- 所有判断逻辑在编译阶段完成,若
static_assert的条件不满足,编译器会直接抛出错误,不会进入运行阶段。
内容的提问来源于stack exchange,提问作者27rabbit
相关产品推荐
相关产品推荐

