2

There is a feature in c++ for forcing compile-time executions of functions on demand, if that is possible. The feature is constexpr functions.

Now at the committee they are trying (I think this is Niccolas Josuttis effort) to give guidelines on when to use constexpr, since in C++14 they relaxed constexpr and there is a potential "risk" to use constexpr everywhere.

I wonder, in the first place, why it was decided that functions are decorated with constexpr.

In D you can do this:

//No special signature, as in C++'s constexpr
uint factorial(uint n) { ...}

//Calculate at compile-time. Note that the request is just made at the point of use
static val = fac(5);
  • Why in C++ it was decided that you must decorate the function signature in the first place?
  • Could this rule be relaxed for C++17? This would eliminate the need to design a guideline and would make it more flexible. You would use constexpr where you use staticin D and get rid of the other part.
Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
Germán Diago
  • 7,473
  • 1
  • 36
  • 59
  • 1
    `constexpr` functions are not guaranteed to be evaluated at compile time, even if the arguments are all constant expressions. There are instances where the standard does require their evaluation at compile time, but it's not true in general, and there really are cases where compilers let such functions be evaluated at run time. Based on your D example, it looks like C++ `constexpr` is the rough equivalent of a D plain function. –  Jun 07 '14 at 16:14
  • Sorry. What I meant is that you can force to be evaluated at compile-time when you use constexpr somewhere and give constexpr args or constants, I change it. – Germán Diago Jun 07 '14 at 16:51
  • I have no idea what you're asking, but if I had to try to interpret it, I'd say that you're proposing the equivalent for `constexpr` of "remove the keyword `const` from the language and hope that people just don't modify the things I don't want them to modify". Am I right? – Lightness Races in Orbit Jun 07 '14 at 17:07
  • 1
    I am proposing that you don't need to mark functions as constexpr and that you use constexpr only at the call site, just as you can do now. That wouldn't make consexpr funcions special in the sense that you don't need to mark them explicitely. It is what D already does. I wonder whey they took the other approach in c++. Which were the constraints? – Germán Diago Jun 07 '14 at 17:09
  • @germandiago I believe the reasoning is provided exhastively in the now linked question. For a concrete example, `static const x = foo();` behaves differently (both in terms of compiler workload, and behaviour) if `foo` is `constexpr`. – Yakk - Adam Nevraumont Jun 07 '14 at 17:22

0 Answers0