How can I get the depth of a multidimensional std::vector at compile time?

前端 未结 3 402
鱼传尺愫
鱼传尺愫 2021-02-01 01:37

I have a function that takes a multidimensional std::vector and requires the depth (or the number of dimensions) to be passed in as a template parameter. Instead of

3条回答
  •  被撕碎了的回忆
    2021-02-01 01:56

    You can define the following class template vector_depth<> which matches any type:

    template
    struct vector_depth {
       static constexpr size_t value = 0;
    };
    

    This primary template corresponds to the base case that ends the recursion. Then, define its corresponding specialization for std::vector:

    template
    struct vector_depth> {
       static constexpr size_t value = 1 + vector_depth::value;
    };
    

    This specialization matches an std::vector and corresponds to the recursive case.

    Finally, define the function template, GetDepth(), that resorts to the class template above:

    template
    constexpr auto GetDepth(T&&) {
       return vector_depth>>::value;
    }
    

    Example:

    auto main() -> int {
       int a{}; // zero depth
       std::vector b;
       std::vector> c;
       std::vector>> d;
    
       // constexpr - dimension determinted at compile time
       constexpr auto depth_a = GetDepth(a);
       constexpr auto depth_b = GetDepth(b);
       constexpr auto depth_c = GetDepth(c);
       constexpr auto depth_d = GetDepth(d);
    
       std::cout << depth_a << ' ' << depth_b << ' ' << depth_c << ' ' << depth_d;
    }
    

    The output of this program is:

    0 1 2 3
    

提交回复
热议问题