我应该如何在编译时检查整数数组是否是回文(例如 1 3 10 3 1 是回文)?
可能的框架可以是:
template <int...>
class IntArray;
template <int... values>
class Palindrome<IntArray<values...>>;
static_assert(Palindrome<IntArray<1, 2, 1>>::check == true);
我知道这个问题似乎毫无意义,但我只是好奇我应该使用的语法。
我读过有关编译时斐波那契计算的帖子和博客,但没有得到任何启发。
有人可以告诉我如何实现这个或者我应该阅读/学习什么材料吗?
提前致谢。
我对编译时编程知之甚少,我能用编译时编程解决的最复杂的问题是这样的:
template<int a, int b>
struct max_template {
static constexpr int value = a > b ? a : b;
};
constexpr int max_fun(int a, int b) {
return a > b ? a : b;
}
// or
template <unsigned N>
struct Fibonacci
{
enum
{
value = Fibonacci<N-1>::value + Fibonacci<N-2>::value
};
};
template <>
struct Fibonacci<1>
{
enum
{
value = 1
};
};
template <>
struct Fibonacci<0>
{
enum
{
value = 0
};
};
它在 C++17 中或多或少是微不足道的,除非你有使用纯函数构造的限制:
template<int...>
class IntArray;
template<class>
struct IsPalindrome;
template<int... values>
struct IsPalindrome<IntArray<values...>> {
static constexpr bool value = []{
constexpr int arr[] = {values...};
constexpr std::size_t N = std::size(arr);
for (std::size_t i = 0; i < N / 2; ++i)
if (arr[i] != arr[N - 1 - i])
return false;
return true;
}();
};
static_assert( IsPalindrome<IntArray<0, 1, 2, 3, 2, 1, 0>>::value);
static_assert(!IsPalindrome<IntArray<0, 1, 2, 3, 4, 1, 0>>::value);