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

前端 未结 3 457
鱼传尺愫
鱼传尺愫 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:52

    Assuming that a container is any type that has value_type and iterator member types (standard library containers satisfy this requirement) or a C-style array, we can easily generalize Cruz Jean's solution:

    template
    struct rank : std::integral_constant {};
    
    // C-style arrays
    template
    struct rank 
        : std::integral_constant::value> {};
    
    template
    struct rank 
        : std::integral_constant::value> {};
    
    // Standard containers
    template
    struct rank> 
        : std::integral_constant::value> {};
    
    int main() {
        using T1 = std::list, 4>>>;
        using T2 = std::list[4]>>;
    
        std::cout << rank();  // Output : 4
        std::cout << rank();  // Output : 4
    }
    

    Container types can be further restricted if needed.

提交回复
热议问题