get second dimension of the array using std::extent

Viewed 101

I'm trying to get the second dimension of a 2D array using std::extent, but getting output as 0.

#include <iostream>
#include <type_traits>


int32_t main(int32_t argc, char *argv[]) {
    int32_t arr[10][100];
    
    std::cout << "first dim: " << sizeof(arr) / sizeof(*arr) << std::endl;
    std::cout << "second dim: " << sizeof(*arr) / sizeof(**arr) << std::endl;
    
    std::cout << "rank: " << std::rank<decltype(arr)>{} << std::endl;
    std::cout << "first dim: " << std::extent<decltype(arr)>{} << std::endl;
    std::cout << "second dim: " << std::extent<decltype(*arr)>{} << std::endl;
    
    return EXIT_SUCCESS;
}
2 Answers

To get the second dimension use this:

std::cout << "second dim: " << std::extent<decltype(arr),1>{} << std::endl; 
                                                   //    ^ second dimension !

The reason you get the result of 0 is that decltype(*arr) has type int32_t(&)[100], which is a reference to an array type. std::extent returns 0 unless you pass it exactly an array type.

You can get the expected result by removing the reference like this:

std::extent<std::remove_reference_t<decltype(*arr)>>{}  // 100

Here's a demo.

Related