Constraining variable templates and template aliases
As you well know, apart from function templates and class templates we also have variable templates and alias templates in C++. These make no exception of the need to define constraints. The same rules for constraining the template arguments discussed so far apply to these two. In this section, we will demonstrate them shortly. Let’s start with variable templates.
It is a typical example to define the PI
constant for showing how variable templates work. Indeed, it is a simple definition that looks as follows:
template <typename T> constexpr T PI = T(3.1415926535897932385L);
However, this only makes sense for floating-point types (and maybe other types such as decimal
, which does not exist in C++ yet). Therefore, this definition should be restricted to floating-point types, as follows:
template <std::floating_point T> constexpr T PI = T(3.1415926535897932385L); std::cout << PI<double> <...