Question:
While studying the new C++ standard, I came across the innovation “ variable templates ”
The template syntax is as follows:
template < typename T >
constexpr T value = T(1234);
About the application of the template it is written:
This feature allows you to create and use
constexpr
variable templates, for a more convenient combination with template algorithms.
I don't quite understand how such a variable would be used in a template algorithm . Could you give some examples of using this mechanism? I also don’t understand why it is impossible to replace such a template constexpr
expression with a non- template one, because we specify the value explicitly, respectively, and we can write (deduce) the type explicitly.
Answer:
There is an example in the standard:
template<class T>
constexpr T pi = T(3.1415926535897932385L);
template<class T>
T circular_area(T r) {
return pi<T> * r * r;
}
Here the variable template allows you to get a constant of the desired size – float/double/etc.
Another popular use is to replace is_some<T>::value
with is_some_v<T>
, e.g.
template< class T, class U >
inline constexpr bool is_same_v = is_same<T, U>::value; // C++17