编译时回文检查

27r*_*bit 2 c++ templates palindrome compile-time c++17

我应该如何在编译时检查整数数组是否是回文(例如 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);
Run Code Online (Sandbox Code Playgroud)

我知道这个问题似乎毫无意义,但我只是好奇我应该使用的语法。

我读过有关编译时斐波那契计算的帖子和博客,但没有发现任何启发性的内容。

谁能告诉我如何实现这个?

我对编译时编程知之甚少;我可以通过编译时编程解决的最复杂的问题是这样的:

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
    };
};
Run Code Online (Sandbox Code Playgroud)

Evg*_*Evg 7

它在 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);
Run Code Online (Sandbox Code Playgroud)

纯函数式实现比较冗长,但即使在 C++11 中也能工作:

template<class IntArray, int>
struct PushBack;

template<int... values, int value>
struct PushBack<IntArray<values...>, value> {
    using type = IntArray<values..., value>;
};

template<class IntArray>
struct Reverse;

template<>
struct Reverse<IntArray<>> {
    using type = IntArray<>;
};

template<int first, int... rest>
struct Reverse<IntArray<first, rest...>> {
    using type = typename PushBack<
        typename Reverse<IntArray<rest...>>::type, 
        first
    >::type;
};

template<class IntArray>
using IsPalindrome = 
    std::is_same<IntArray, typename Reverse<IntArray>::type>;
Run Code Online (Sandbox Code Playgroud)

  • @27rabbit 添加了一个纯函数式的实现,如“斐波那契”的实现。 (2认同)