Search code examples
c++templatesconstexprconstexpr-function

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


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

Solution

  • 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