有一天我问了一个非常类似的问题 https://stackoverflow.com/questions/59490698/how-can-i-get-the-depth-of-a-multidimensional-stdvector-at-compile-time关于嵌套向量,但我遇到了另一个让我难倒的问题。我需要在编译时获取嵌套向量的最内部类型,以便我可以使用它作为模板参数传递。
例如,如果我有这个嵌套向量:
std::vector<std::vector<std::vector<int>>> v;
我需要一种方法来提取int
所以我可以调用一个函数,该函数采用嵌套向量并对元素进行处理,如下所示:
foo<int>(v);
但问题是这个函数应该能够处理任何深度、任何类型的嵌套向量。当我打电话时foo
我希望自动为我推导出内部类型。
所以也许这个调用看起来像这样:
foo<inner_type_t<v>>(v);
Where inner_type_t
是某种形式的递归模板,可以解析为int
当给予v
.
我认为该解决方案与其他问题的解决方案类似,但我一直无法解决......在递归模板方面我仍然有点新手。
Edit:
这是我到目前为止所拥有的......
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();
}
output:
struct inner_type<class std::vector<int,class std::allocator<int> > >