Tutorial by Examples

Factorials can be computed at compile-time using template metaprogramming techniques. #include <iostream> template<unsigned int n> struct factorial { enum { value = n * factorial<n - 1>::value }; }; template<> struct factorial<0> { ...
Often, we need to perform an operation over every element in a variadic template parameter pack. There are many ways to do this, and the solutions get easier to read and write with C++17. Suppose we simply want to print every element in a pack. The simplest solution is to recurse: C++11 void print...
Since C++14, the standard provides the class template template <class T, T... Ints> class integer_sequence; template <std::size_t... Ints> using index_sequence = std::integer_sequence<std::size_t, Ints...>; and a generating metafunction for it: template <class T, T N&g...
A simple way of selecting between functions at compile time is to dispatch a function to an overloaded pair of functions that take a tag as one (usually the last) argument. For example, to implement std::advance(), we can dispatch on the iterator category: namespace details { template <clas...
It is possible to detect whether an operator or function can be called on a type. To test if a class has an overload of std::hash, one can do this: #include <functional> // for std::hash #include <type_traits> // for std::false_type and std::true_type #include <utility> // for s...
With C++11 and higher calculations at compile time can be much easier. For example calculating the power of a given number at compile time will be following: template <typename T> constexpr T calculatePower(T value, unsigned power) { return power == 0 ? 1 : value * calculatePower(value,...
When implementing SFINAE using std::enable_if, it is often useful to have access to helper templates that determines if a given type T matches a set of criteria. To help us with that, the standard already provides two types analog to true and false which are std::true_type and std::false_type. The...
C++11 The type std::conditional in the standard library header <type_traits> can select one type or the other, based on a compile-time boolean value: template<typename T> struct ValueOrPointer { typename std::conditional<(sizeof(T) > sizeof(void*)), T*, T>::type vop; }...
C++11 It's possible to write a generic function (for example min) which accepts various numerical types and arbitrary argument count by template meta-programming. This function declares a min for two arguments and recursively for more. template <typename T1, typename T2> auto min(const T1 &...

Page 1 of 1