2
\$\begingroup\$

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
\$\endgroup\$
  • 3
    \$\begingroup\$ I think "useful" and "impressive" are too subjective and broad for this challenge to be a good fit for the site. \$\endgroup\$ – Alex A. Jul 20 '15 at 19:52
  • \$\begingroup\$ That's why it's a popularity contest :) I'll let the voting system decide \$\endgroup\$ – Mark K Cowan Jul 20 '15 at 20:06
  • 2
    \$\begingroup\$ Popularity contests still need the task to be specific and well-defined. I suggest taking a look at the popularity contest tag wiki. \$\endgroup\$ – Alex A. Jul 20 '15 at 20:12