Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Why the constexpr keyword?

30 views
Skip to first unread message

Marcel Mueller

unread,
Apr 29, 2016, 2:57:44 AM4/29/16
to
C++11 introduced constexpr for (some) strictly deterministic and
functional code. But now I need to write constexpr at many places in the
code to get the benefits from it.

Shouldn't it be up to the compiler to check whether a function or
constructor is constexpr or not? I mean similar to inline or register
which are no much more than optional hints nowadays. (Yes, I know,
inline implies weak linkage.)

I would prefer when every thing gets constexpr automatically wherever
possible. What should be the motivation to prevent a function to be
constexpr?
I could write a static assertion if I need to check whether an
expression satisfies this constraint. The compiler could do the same
when it requires a constexpr.

In fact this behavior was implemented from the very early days of the C
language as you always could write
int array[3+4];
where 3+4 is nothing else but a constexpr.

So I can't get why there is a need for the new keyword and the resulting
refactoring of library code for C++11 and above.


Marcel

Alf P. Steinbach

unread,
Apr 29, 2016, 3:43:42 AM4/29/16
to
On 29.04.2016 08:57, Marcel Mueller wrote:
>
> I can't get why there is a need for the new keyword and the resulting
> refactoring of library code for C++11 and above.

It means the compiler can (and must) tell you wherever you write
`constexpr` code that is beyond what can be `constexpr`, e.g.
inadvertently using dynamic allocation by involving a `std::string`.

So `constexpr` is part of the usual static type checking scheme.

Also, without it checking whether code could be evaluated at compile
time would incur some extra overhead for separate compilation (with
effectively whole program optimization invoked). Today compilers have
whole program optimization as an option. Because it has a cost, in
compilation time, size of object files, and restriction of use of features.


Cheers & hth.,

- Alf

0 new messages