std::extent() template in C++

In this post, we will learn about std::extent() template in C++. We have to use <type_traits> library which is a part of C++ STL. The std::extent() is used to find out the number of elements in a particular dimension of an array type. This will be easier to understand with the help of an example. You are given an array type P[][3][4], here the rank of P = 3.

So, the extent of the array P with respect to a dimension is given by the following notation:

std::extent<P, Dimension>::value


std::extent<P, 0>::value = 0 (Since we haven’t specified the bounds for the first dimension)

std::extent<P, 1>::value = 3 (Since the first dimension of array type P[][3][4] is 3)

std::extent<P, 2>::value = 4 (Since the second dimension of array type P[][3][4] is 4)

std::extent<P, 3>::value = 0 (Since dimension = rank, so extent is 0)

The std::extent() template is :

template< class P, unsigned X = 0>
struct extent;

The “::value” is a helper variable that tells us the number of elements along the Xth value of array type P.

Also, note that if you don’t pass any dimension argument by default it is set to 0.

C++ program to demonstrate std::extent() template

#include <iostream> 
#include <type_traits> 
using namespace std; 

int main() 

        typedef int P[][3][4];
        cout <<"Passing No Dimension argument,By default dimension is set to 0, extent = " <<  extent<P>::value << endl;
        cout << "Dimension 0, extent = " << extent<P, 0>::value << endl;
        cout << "Dimension 1, extent = " << extent<P, 1>::value << endl;//P[][3][4]
        cout << "Dimension 2, extent = " << extent<P, 2>::value << endl;
        cout << "Dimension 3, extent = " << extent<P, 3>::value << endl; //if rank==dimension then extent = 0.

        return 0;

Output for the above Code

std::extent() template in C++

std::has_virtual_destructor in C++ with examples

Leave a Reply

Your email address will not be published. Required fields are marked *