如何在编译时推断嵌套 std::vector 的内部类型? [英] How can I deduce the inner type of a nested std::vector at compile time?

查看:40
本文介绍了如何在编译时推断嵌套 std::vector 的内部类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

前几天我问了一个非常类似问题 关于嵌套向量,但我遇到了另一个让我感到困惑的问题.我需要在编译时获取嵌套向量的最内层类型,以便我可以使用它作为模板参数传递.

The other day I asked a very similar question about nested vectors, but I've come across another problem that has me stumped. I need to get the innermost type of a nested vector at compile time so I can use it to pass as a template argument.

例如,如果我有这个嵌套向量:

For example if I have this nested vector:

std::vector<std::vector<std::vector<int>>> v;

我需要一种提取 int 的方法,以便我可以调用一个函数,该函数采用嵌套向量并处理如下元素:

I need a way to extract int so I can call a function that takes a nested vector and works on the elements like this:

foo<int>(v);

除了问题是这个函数应该能够处理包含任何类型的任何深度的嵌套向量.当我调用 foo 时,我希望自动为我推导出内部类型.

Except the catch is this function should be able to work on nested vectors of any depth that hold any type. And when I call foo I want the inner type to be automatically deduced for me.

所以调用可能看起来像这样:

So maybe the call would look something like this:

foo<inner_type_t<v>>(v);

其中 inner_type_t 是某种形式的递归模板,当给定 v 时,它会解析为 int.

Where inner_type_t is some form of recursive template that resolves to int when given v.

我认为该解决方案将类似于另一个问题的解决方案,但我一直无法解决...在递归模板方面,我仍然是一个新手.

I assume the solution will be similar to that of the other question but I haven't been able to work it out... I'm still a bit of a novice when it comes to recursive templates.

这是我目前所拥有的...

Here is what I have so far...

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

template <typename T>
struct inner_type<std::vector<T>>
{
    using type = inner_type<T>;
};

int main()
{
    std::vector<std::vector<int>> v  = {
        { 1, 2}, {3, 4}
    };

    std::cout << typeid(inner_type<decltype(v)>::type).name();
}

输出:

struct inner_type<class std::vector<int,class std::allocator<int> > >

推荐答案

@tjwrona1992 的解决方案没问题,但不允许具有不同分配器的向量.另外,让我们使用 _t 版本的特征使这个 C++14 友好.

@tjwrona1992's solution is ok, but doesn't allow for vectors with different allocators. Also, let's make this C++14-friendly with an _t version of the trait.

这应该可以解决问题:

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

template<class T, class Alloc>
struct inner_type<std::vector<T, Alloc>> { using type = typename inner_type<T>::type; };

template<class T>
using inner_type_t = typename inner_type<T>::type;

此外,对于类型名称,您应该使用在此处实现的type_name() 函数 对于 C++14 或此处对于 C++17.

Also, for the type name, you should using the type_name() function implemented here for C++14 or here for C++17.

实时查看...

这篇关于如何在编译时推断嵌套 std::vector 的内部类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆