Posted Joe Chu cppa minute read (About 223 words)0 visits
Variable Template
Since C++14
1. Introduction
Variable templates in C++ are a feature introduced in C++14 that allows you to define a variable that is parameterized by one or more template parameters. This is similar to how you define template functions or classes, but for variables. Variable templates can be useful for defining constants or other variables that need to vary based on the type or other template parameters.
template<typename T> constexpr T pi = T(3.1415926535897932385L); // variable template // function template template<typename T> T circular_area(T r){ return pi<T> * r * r; // pi<T> is a variable template instantiation }
When used within class scope, variable templates usually declare as static.
1 2 3 4 5 6 7 8 9 10 11 12 13 14
template<typename T> classMathConstants { public: staticconstexpr T pi = T(3.1415926535897932385); staticconstexpr T e = T(2.7182818284590452353); template<int N> staticconstexpr T power_of_two = T(1 << N); };