1.4 KiB
1.4 KiB
Variable templates (C++17)
Why?
Eg. different precision
template<class T>
constexpr T pi = T(3.1415926535897932385L);
template<class T>
T circular_area(T r) { return pi<T> * r * r; }
But it is really rarely used.
Specialization example #2 - field values
Remember this code?
#include <iostream>
template<typename T> // primary template
struct is_int {
static constexpr bool value = false;
};
template<> // explicit specialization for T = int
struct is_int<int> {
static constexpr bool value = true;
};
template<typename T>
constexpr bool is_int_v = is_int<T>::value;
int main() {
std::cout << is_int_v<char> << '\n'; // prints 0 (false)
std::cout << is_int_v<int> << '\n'; // prints 1 (true)
return 0;
}
We mainly use template variables as helpers to class template field values.
Check out type_traits on cppreference.com
Every trait has a corresponding helper variable template.
Exercise
Write a variable template is_int_key_v. It should return a value of the is_int_key field in a given template type.