Variable Templates (C++14)
Templated variables for type-dependent constants
Overview
C++14 introduces variable templates, allowing you to define templated variables that can have different values depending on the type.
// Define PI with different precision for each type
template<typename T>
constexpr T pi = T(3.1415926535897932385L);
// Usage
pi<double>; // 3.1415926535897932385
pi<float>; // 3.1415927 (float precision)
// Type traits as variable templates
template<typename T>
constexpr bool is_pointer_v = std::is_pointer<T>::value;
// C++17 shortcut: std::is_pointer_v<T> is a variable templatePractical Examples
// Constants for different types
template<typename T>
constexpr T e = T(2.71828182845904523536L);
template<typename T>
constexpr T sqrt2 = T(1.4142135623730950488L);
// Type-dependent limits
template<typename T>
constexpr T max_value = std::numeric_limits<T>::max();
// Usage
auto pi_d = pi<double>; // double precision
auto pi_f = pi<float>; // float precision