Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Am I correct in understanding that, contrary to the Turing completeness of C++ template instantiations, the (compile time) computational power of these Constant Expressions thing is intentional?


Yes. A "constexpr" function can use a large subset of C++, including calls to other constexpr functions, but the compiler guarantees to evaluate it at compile time, so you can use it where the compiler expects a compile-time constant.


> the compiler guarantees to evaluate it at compile time

It doesn't guarantee that.

For example:

  static constexpr int fac(int x) { return x <= 1 ? 1 : x * fac(x - 1); }
  int f() {
    return fac(4); // May or may not be evaluated at run-time.
  }
  char arr[fac(4)]; // fac(4) is evaluated at compile-time.


I should have said, "guarantees that it can evaluate it at compile time if needed, such that you can use it where the compiler expects a compile-time constant expression". Yes, the compiler can choose to defer it until runtime in some cases.


Can it be forced to be computed at compile-time, by static_assert'ing on the result of the computation?


Yes, among other things. As long as a program can't tell the difference (as per the as-if rule), the compiler is free to delay tjee evaluation till runtime.


Much saner than abusing templates for this purpose. Faster, better error messages, and miles more readable. I look forward to the day when all the metaprogramming inside boost is rewritten to use constexpr.


Metaprogramming is different than compile time programming. I agree with templates being abused as a compile time programming language but they are used as Metaprogramming just fine (well, or not but that's their primary usage)




Consider applying for YC's Summer 2026 batch! Applications are open till May 4

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: