Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get second dimension of the array using std::extent

Tags:

c++

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;
}
like image 789
Harry Avatar asked Nov 27 '20 13:11

Harry


2 Answers

To get the second dimension use this:

std::cout << "second dim: " << std::extent<decltype(arr),1>{} << std::endl; 
                                                   //    ^ second dimension !
like image 193
463035818_is_not_a_number Avatar answered Oct 23 '22 11:10

463035818_is_not_a_number


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.

like image 37
cigien Avatar answered Oct 23 '22 12:10

cigien