C++ 14 – Template related features
From C++ 14 onwards, templates are allowed on variables. Also, C++ 14 introduced std::enable_if_t, which can be used for conditional statements inside function templates.
Let us see step-by-step using a simple C++ example program. The program is available for download at https://github.com/codeversionmaster/cplusplus/blob/cplusplus17/cpp14-templates.cpp.
The program starts with header files, as shown.
The variable template is as shown. The template declaration is the same as a function or class template. But now the template argument is used on a variable – T pi and T(<value>).
#include <iostream>
#include <type_traits>
// Variable template for pi
template<typename T>
constexpr T pi = T(3.1415926535897932385);
Using std::enable_if_t, we check if the value is an arithmetic variable such as int or float, then proceed with the function definition using the function template.
// Function template with std::enable_if_t
template<typename T, std::enable_if_t<std::is_arithmetic<T>::value, int> = 0>
T multiply_pi(T value) {
return value * pi<T>;
}
Here, we can call the template variable and template function (that used std::enable_if_t) by passing both int and float values.
int main() {
int int_val = 3;
double double_val = 3.5;
// Use variable template for pi
std::cout << "Value of pi (float): " << pi<float> << std::endl;
std::cout << "Value of pi (double): " << pi<double> << std::endl;
// Use std::enable_if_t in a function template
std::cout << "3 * pi (integer): " << multiply_pi(int_val) << std::endl;
std::cout << "3.5 * pi (double): " << multiply_pi(double_val) << std::endl;
return 0;
}
You can compile and run the program as shown.
$ g++ -std=c++14 cpp14-templates.cpp -o cpp14-templates
$ ./cpp14-templates
Value of pi (float): 3.14159
Value of pi (double): 3.14159
3 * pi (integer): 9
3.5 * pi (double): 10.9956