gpt4 book ai didi

c++ - 如何在编译时推断嵌套std::vector的内部类型?

转载 作者:行者123 更新时间:2023-12-04 22:09:34 25 4
gpt4 key购买 nike

前几天我问了一个关于嵌套 vector 的非常 similar question,但我遇到了另一个让我难倒的问题。我需要在编译时获取嵌套 vector 的最内层类型,以便我可以使用它作为模板参数传递。
例如,如果我有这个嵌套 vector :

std::vector<std::vector<std::vector<int>>> v;
我需要一种提取 int 的方法,以便我可以调用一个函数,该函数采用嵌套 vector 并处理如下元素:
foo<int>(v);
除了问题是这个函数应该能够处理包含任何类型的任何深度的嵌套 vector 。当我调用 foo 时,我希望为我自动推导出内部类型。
所以也许调用看起来像这样:
foo<inner_type_t<v>>(v);
其中 inner_type_t 是某种形式的递归模板,当给定 int 时,它​​会解析为 v
我认为该解决方案将类似于另一个问题的解决方案,但我无法解决它......在递归模板方面,我仍然有点新手。
编辑:
这是我到目前为止...
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 的解决方案没问题,但不允许具有不同分配器的 vector 。此外,让我们使用 _t 版本的 trait 使这个 C++14 友好。

这应该可以解决问题:

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;

此外,对于类型名称,您应该使用为 C++14 实现的 here 或为 C++17 实现的 heretype_name() 函数。

See it working live...

关于c++ - 如何在编译时推断嵌套std::vector的内部类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59503567/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com