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;
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);
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);
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();
}
output:
struct inner_type<class std::vector<int,class std::allocator<int> > >
Wow I was really close haha, got it to work!
I just had to change the template specialization slightly to properly get the type recursively.
template <typename T>
struct inner_type
{
using type = T;
};
template <typename T>
struct inner_type<std::vector<T>>
{
// Had to change this line
using type = typename inner_type<T>::type;
};
int main()
{
std::vector<std::vector<int>> v = {
{ 1, 2}, {3, 4}
};
std::cout << typeid(inner_type<decltype(v)>::type).name();
}
Output:
int
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With