Variable Templates | C++

/Variable Templates | C++

The variable template is one of the major proposals in Standard C++14. The main purpose of the variable template is to simplify definitions and uses of parameterized constants. With variable templates of C++14, manipulation of constant values with various types can be significantly simplified as shown in below example. PI is declared as a variable template, and given a constant value 3.1415926535897932385 with type conversion. If the use of template is initialized with PI<int>, PI is initialized with a type conversion of 3.1415926535897932385.

template<typename T>
constexpr T PI = T(3.1415926535897932385);

template<typename T>
T area (T r) {
  return PI<T> * r * r;
}

int main()
{
  printf("PI: %d, area: %d\n", PI<int>, area(2));         // PI: 3, area: 12
  printf("PI: %lf, area: %lf\n", PI<double>, area(2.0));  // PI: 3.141593, area: 12.566371
  return 0;
}

 

Templates can also be applied to non-constant variables. For example, when assigning a different value, 0.618, to PI<float>, PI<double> is not changed. It is not difficult to understand because the variable follows the rules of templates that initialize the instance for each use.

template<typename T>
T Value = T(3.1415926535897932385);

int main()
{
  Value<float> = 0.6180339887498948482;
  
  printf("%f\n", Value<float>);      // Output : 0.618034
  printf("%lf\n", Value<double>);    // Output : 3.141593

  return 0;
}

 

September 16th, 2019|Categories: Programming|Tags: |
avatar
  Subscribe  
Notify of