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.

2. A Starter Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
#include <memory>
#include <vector>

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
}

int main() {
std::cout << "circular_area<int>(1) = " << circular_area<int>(1) << '\n';
std::cout << "circular_area<float>(1.) = " << circular_area<float>(1.) << '\n';
std::cout << "circular_area<double>(1.) = " << circular_area<double>(1.) << '\n';
}
1
2
3
circular_area<int>(1) = 3
circular_area<float>(1.) = 3.14159
circular_area<double>(1.) = 3.14159

3. In Class Scope

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>
class MathConstants {
public:
static constexpr T pi = T(3.1415926535897932385);
static constexpr T e = T(2.7182818284590452353);

template<int N>
static constexpr T power_of_two = T(1 << N);
};

// Usage
double pi_value = MathConstants<double>::pi;
float e_value = MathConstants<float>::e;
int eight = MathConstants<int>::power_of_two<3>;

4. Fibonacci Using Variable Template

1
2
3
4
5
6
7
8
9
10
template<int N>
constexpr int fibonacci = fibonacci<N-1> + fibonacci<N-2>;

// specialized template for base case 0
template<>
constexpr int fibonacci<0> = 0;

// specialized template for base case 1
template<>
constexpr int fibonacci<1> = 1;

References

Author

Joe Chu

Posted on

2024-07-13

Updated on

2024-07-13

Licensed under

Comments