Defining variable templates
Variable templates were introduced in C++14 and allow us to define variables that are templates either at namespace scope, in which case they represent a family of global variables, or at class scope, in which case they represent static data members.
A variable template is declared at a namespace scope as shown in the following code snippet. This is a typical example that you can find in the literature, but we can use it to elaborate on the benefits of variable templates:
template<class T> constexpr T PI = T(3.1415926535897932385L);
The syntax is similar to declaring a variable (or data member) but combined with the syntax for declaring templates.
The question that arises is how variable templates are actually helpful. To answer this, let's build up an example to demonstrate the point. Let's consider we want to write a function template that, given the radius of a sphere, returns its volume. The volume of a sphere is