获取多维变量的根类型 std::array

Getting root type of multidimensional variadic std::array

我嵌套了 std::array 哪个维度由模板参数处理 std::array

我想知道如何在 std::array, 2> 中获取 int 类型。

在这种情况下,我们可以只做 std::array, 2>::value_type::value_type,但我怎么能做到这一点而不必放置与尺寸一样多的 value_type 吗?

您可以使用基本的递归技术:

template <typename T>
struct nested_value_type { using type = T; };

template <typename T, std::size_t N>
struct nested_value_type<std::array<T, N>>
{
    using type = typename nested_value_type<T>::type;
};

为方便起见,提供一个别名模板:

template <typename T>
using nested_value_type_t = typename nested_value_type<T>::type;

瞧瞧:

static_assert(std::is_same_v<
    nested_value_type_t<std::array<int, 1>>,
    int
>);

static_assert(std::is_same_v<
    nested_value_type_t<std::array<std::array<float, 1>, 1>>,
    float
>);

static_assert(std::is_same_v<
    nested_value_type_t<std::array<std::array<std::array<char, 1>, 1>, 1>>,
    char
>);

live example on godbolt.org


使用 C++20 的 std::type_identity:

稍微短一点
template <typename T>
struct nested_value_type : std::type_identity<T> { };

template <typename T>
using nested_value_type_t = typename nested_value_type<T>::type;

template <typename T, std::size_t N>
struct nested_value_type<std::array<T, N>> 
    : std::type_identity<nested_value_type_t<T>> { };