Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A constexpr function that calculates how deep a std::vector is nested [duplicate]

Is there a way to write a constexpr function that returns how deep a std::vector is nested?

Example:

get_vector_nested_layer_count<std::vector<std::vector<int>>>() // 2
get_vector_nested_layer_count<std::vector<std::vector<std::vector<float>>>>() // 3
like image 777
palapapa Avatar asked Aug 24 '26 05:08

palapapa


1 Answers

The easy way is to use recursion

#include <vector>

template<class T>
constexpr bool is_stl_vector = false;
template<class T, class Alloc>
constexpr bool is_stl_vector<std::vector<T, Alloc>> = true;

template<class T>
constexpr std::size_t get_vector_nested_layer_count() {
  if constexpr (is_stl_vector<T>)
    return 1 + get_vector_nested_layer_count<typename T::value_type>();
  else
    return 0;
};

Demo

like image 187
康桓瑋 Avatar answered Aug 26 '26 21:08

康桓瑋



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!