@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