c++c++11metaprogrammingcomputation-theoryconstexpr

Is constexpr-based computation Turing complete?


We know that C++ template metaprogramming is Turing complete, but preprocessor metaprogramming is not.

C++11 gives us a new form of metaprogramming: computation of constexpr functions. Is this form of computation Turing-complete? I am thinking that since recursion and the conditional operator (?:) are allowed in constexpr functions, it would be, but I would like someone with more expertise to confirm.


Solution

  • tl;dr: constexpr in C++11 was not Turing-complete, due to a bug in the specification of the language, but that bug has been addressed in later drafts of the standard, and clang already implements the fix.

    constexpr, as specified in the ISO C++11 international standard, is not Turing-complete. Sketch proof:

    However, since the publication of the C++11 standard, the situation has changed.

    The problem described in Johannes Schaub's answer to std::max() and std::min() not constexpr was reported to the C++ standardization committee as core issue 1454. At the February 2012 WG21 meeting, we decided that this was a defect in the standard, and the chosen resolution included the ability to create values of class types with pointer or reference members that designate temporaries. This allows an unbounded quantity of information to be accumulated and processed by a constexpr function, and is sufficient to make constexpr evaluation Turing-complete (assuming that the implementation supports recursion to an unbounded depth).

    In order to demonstrate the Turing-completeness of constexpr for a compiler that implements the proposed resolution of core issue 1454, I wrote a Turing-machine simulator for clang's test suite:

    https://github.com/llvm/llvm-project/blob/main/clang/test/SemaCXX/constexpr-turing.cpp

    Clang 3.1 and g++ 9 onwards both implement the fixed rule in their C++11 modes, and can handle that example.