gdo...@gmail.com <
gdo...@gmail.com> wrote:
> is this one of those things where the committee had nothing better to do? ok, maybe I haven't got to the point where I see the demand for such, but I will be open-minded and use it when I see an opportunity.
>
> prevents ..., more intuitive ..., easier to type than ..., more expressive than ..., solves the problem of ..., well I'm sure I'll see all of that at some point.
constexpr alleviates a serendipitous problem that manifested itself all the
way back in the early days of C++98 (perhaps even before).
You see, the template mechanism was originally designed to merely allow
writing generic classes and generic functions, where you just implement the
class or function once, but it can be used for any type (that's compatible
with the implementation): The compiler automatically generates a version
of the implementation where the types have been replaced. Thus it's much
easier to use the same code for multiple types (and the code is ostensibly
as optimized for that type as possible).
However, it was quite soon discovered that, serendipitously, the C++
template mechanism could be used for a limited form of compile-time
programming. The template mechanism almost forms a "language within
a language", where using its own peculiar syntax you can do all kinds
of calculations at compile time. The so-called "template metaprogramming"
paradigm was born.
It was soon developed into a surprisingly complex "sub-language" of C++.
You could have linked lists, with all typical list operations (appending,
splicing, splitting, traversing, etc.) and you could do all sorts of
calculations, all at compile time.
The problem? Because templates were never designed for this from
the ground up, the syntax is not optimal for this, and "template
metaprogramming" programs tend to be very obfuscated, complicated and
hard to understand. There's also the problem that what you can do with
them is very limited. They are also quite heavy for the compiler to
evaluate (and, in some cases, could require an enormous amount of RAM
because complex "template metaprograms" effectively result in
ginormously long type declarations that may take even megabytes of RAM.)
Thus a better solution was devised for C++11: constexpr.
constexpr allows using C++'s own "normal" syntax, rather than the
complicated template syntax, in order to do those same calculations
much easier. In addition, constexpr code is easier to read, supports
things that template metaprogramming doesn't (such as floating point
calculations), and is much more efficient for the compiler to evaluate
and (usually) requires significantly less RAM. Plus, the exact same code
can be also used at runtime in addition to compile time, so it's yet
again one thing where code repetition is avoided.