@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");
}
'sizeof(a)'=='sizeof(const int *)''。 – kfsone
另外,我猜你在助手中的意思是'symmetric_helper'不是'symmetric_inside'。 – kfsone
你說得對,我糾正了它。 – Dutow