获取多维可变参数std :: array的根类型

问题描述

我嵌套了std :: array,其尺寸由模板参数std :: array 处理。

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

在这种情况下,我们可以只做std :: array ,2> :: value_type :: value_type,但是我如何做到这一点而不必放置尽可能多的value_types尺寸?

解决方法

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

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>,float
>);

static_assert(std::is_same_v<
    nested_value_type_t<std::array<std::array<std::array<char,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,N>> 
    : std::type_identity<nested_value_type_t<T>> { };

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...