Search⌘ K
AI Features

- Examples

Explore practical examples showcasing advanced C++ template features including prime number computation, type trait checks for type manipulation, and various compile-time and runtime power calculations. Learn to apply template metaprogramming and constexpr concepts for efficient and flexible code.

Example 1: Template Prime Number

C++
// templatePrimeNumber.cpp
// Prime number computation by Erwin Unruh
template <int i> struct D { D(void*); operator int(); };
template <int p, int i> struct is_prime {
enum { prim = (p==2) || (p%i) && is_prime<(i>2?p:0), i-1> :: prim };
};
template <int i> struct Prime_print {
Prime_print<i-1> a;
enum { prim = is_prime<i, i-1>::prim };
void f() { D<i> d = prim ? 1 : 0; a.f();}
};
template<> struct is_prime<0,0> { enum {prim=1}; };
template<> struct is_prime<0,1> { enum {prim=1}; };
template<> struct Prime_print<1> {
enum {prim=0};
void f() { D<1> d = prim ? 1 : 0; };
};
#ifndef LAST
#define LAST 18
#endif
int main() {
Prime_print<LAST> a;
a.f();
}

Explanation

This is the original prime number program by Erwin Unruh, which was the starting point of template metaprogramming. Current compilers will not produce the same output as the ancient compiler, which Erwin Unruh used more than 20 years ...