Modern C++ › C++14
Variable Templates and Relaxed constexpr
More powerful compile-time code.
Explanation
Variable templates let a variable be parametrized by type, just as functions and classes could be:
template <typename T>
constexpr T pi = T(3.1415926535897932385L);
pi<double> and pi<float> are different variables. This replaces the C++98 workaround of a class template with a static const member (Pi<T>::value), and it is the basis for the _v helpers in the standard library (std::is_integral_v<T>, C++17).
Relaxed constexpr functions: C++11 allowed only a single return. C++14 allows local variables, if/switch, loops, and mutation of local state, so ordinary-looking code can run at compile time.
[[deprecated("reason")]] (C++14) marks an entity so that use produces a compiler warning with your message. It is the standard way to retire an API gradually.
Example
#include <iostream>
#include <type_traits>
template <typename T>
constexpr T pi = T(3.1415926535897932385L);
template <typename T>
constexpr bool isSmallInt = std::is_integral<T>::value && sizeof(T) <= 2;
constexpr int fibonacci(int n) { // loops and locals are fine in C++14
int a = 0, b = 1;
for (int i = 0; i < n; ++i) {
int next = a + b;
a = b;
b = next;
}
return a;
}
constexpr bool isPrime(int n) {
if (n < 2) return false;
for (int i = 2; i * i <= n; ++i)
if (n % i == 0) return false;
return true;
}
[[deprecated("use newApi() instead")]] void oldApi() {}
void newApi() {}
int main() {
static_assert(fibonacci(10) == 55, "fib");
static_assert(isPrime(97) && !isPrime(91), "primes");
static_assert(isSmallInt<short> && !isSmallInt<long>, "traits");
constexpr double area = pi<double> * 2 * 2; // compile-time constant
std::cout << area << " " << pi<float> << "\n";
int table[fibonacci(6)]; // array of 8 ints
std::cout << sizeof(table) / sizeof(int) << "\n";
newApi();
// oldApi(); // warning: use newApi() instead
return 0;
}
Common pitfalls
- A variable template in a header is fine (implicitly
inline-like for templates), but explicit specializations need care to avoid multiple-definition errors. - Relaxed
constexprstill forbidsgoto,try/catch(until C++20),static/thread_locallocals, and calling non-constexprfunctions in constant contexts. - Compile-time loops that run forever or too long hit the compiler’s step limit.
- A
[[deprecated]]warning can be promoted to an error by-Werror; roll out deprecations deliberately. - Writing
constexpris a promise only for constant expressions; the function may still be used at run time.
Legacy vs modern
// C++98 / C++11: a class template to hold a constant
template <typename T> struct Pi { static constexpr T value = T(3.14159265358979L); };
double a = Pi<double>::value;
// C++14: a variable template
double b = pi<double>;
C++17 adds _v variable templates for all traits; C++20 consteval forces compile-time evaluation.
Exercises
1. Write a variable template zero<T> equal to T{}.
template <typename T> constexpr T zero = T{};