@Dutow 是第一个给出有效答案的人,但这也应该考虑类型推导并能够处理任何类型的数组。
#include <cstddef>
template<typename T, size_t N, size_t O, size_t I>
struct detect_symmetric_array
{
static constexpr bool is_symmetric(T (&array)[N])
{
return array[O] == array[N - O - 1] && detect_symmetric_array<T, N, O + 1, I - 1>::is_symmetric(array);
}
};
template<typename T, size_t N, size_t O>
struct detect_symmetric_array<T, N, O, 1>
{
static constexpr bool is_symmetric(T(&array)[N])
{
return array[O] == array[N - O - 1];
}
};
template<typename T, size_t N>
constexpr bool is_symmetric_array(T (&array)[N])
{
return detect_symmetric_array<T, N, 0, N / 2>::is_symmetric(array);
}
int main(int argc, char** argv)
{
constexpr int first[4] = { 1, 2, 2, 1 }, second[4] = { 1, 2, 3, 4 }, third[5] = {1, 2, 3, 2, 1}, foruth[5] = {1,3,2,4,5};
static_assert(is_symmetric_array(first), "array first should be symmetric");
static_assert(is_symmetric_array(second) == false, "array second should not be symmetric");
static_assert(is_symmetric_array(third), "array third should be symmetric");
static_assert(is_symmetric_array(foruth) == false, "array fourth should not be symmetric");
}