C++ metaprogramming

A completely useless but fun-to-write example for C++ template metaprogramming. Did you ever wanted to calculate the control digit of a UIC wagon number at compile-time? This serves just as an example that any computer algorithm can be implemented in some way in a template metaprogram (template metaprogramming is generally Turing-complete).

#include <iostream>

template <long long u, int m>
struct S
    static long long const val = S<u/10, m%2+1>::val + ((u%10)*m)/10 + ((u%10)*m)%10;

template <int m>
struct S<0, m>
    static long long const val = 0;

template <long long u>
struct UIC
    static long long const val = u*10+(10-S<u,2>::val%10)%10;

int main()
    std::cout << UIC<21812471217LLU>::val << std::endl;
    return 0;

As one would expect, the output is 218124712173 🙂

Leave a Reply