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;
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With