Useful C++ template metaprograms

2

C++ implements a Turing-complete functional programming language which is evaluated at compile time.

Hence, we can use a C++ compiler as an interpreter to run our metaprogram without ever generating code. Unfortunately, static_assert won't allow us to emit our result at compile-time, so we do need* to generate an executable to display the result.

* we can display via a compile-time error in template instantiation, but the result is less readable.

Challenge

Implement a useful or impressive program purely via template metaprogramming. This is a popularity contest, so the code with the most votes wins.

Rules:

  1. Your program must compile against the C++14 standard. This means that the actual compiler you use doesn't matter to anyone else.

    -std=c++14

  2. "External" input is passed via preprocessor definitions.

    -Dparam=42

  3. Output is via a single cout/printf line which does no run-time calculations besides those necessary for stringifying the result, or is via a compile-time error.

    int main(int argc, char **argv) { std::cout << MyMetaProgram<param>::result << std::endl; }


Example: Factorial

bang.h

template <unsigned long long N>
struct Bang
{
    static constexpr unsigned long long value = N * Bang<N-1>::value;
};

template <>
struct Bang<0>
{
    static constexpr unsigned long long value = 1;
};

bang.cpp

#include <iostream>
#include "bang.h"

int main(int argc, char **argv)
{
    std::cout << Bang<X>::value << std::endl;
}

execute

$ g++ -std=c++14 -DX=6 bang.cpp -o bang && ./bang
120

Mark K Cowan

Posted 2015-07-20T19:27:10.493

Reputation: 227

Question was closed 2015-07-20T20:17:22.297

3I think "useful" and "impressive" are too subjective and broad for this challenge to be a good fit for the site. – Alex A. – 2015-07-20T19:52:49.813

That's why it's a popularity contest :) I'll let the voting system decide – Mark K Cowan – 2015-07-20T20:06:26.347

2

Popularity contests still need the task to be specific and well-defined. I suggest taking a look at the popularity contest tag wiki.

– Alex A. – 2015-07-20T20:12:47.637

No answers