Hacker News new | ask | show | jobs
by FpUser 1118 days ago
I would absolutely hate `constexpr` to be implicit and left to be decided by compiler.
3 comments

How D decides it is if the grammar says its a constant-expression, whatever makes up the constant-expression gets evaluated at compile time - functions and all. For example,

    int square(int x) { return x * x; }

    static assert(square(3) == 9);
This allows one to write unit tests that are checked at compile time, whereas:

    int main() { assert(square(3) == 9); }
is always a runtime check.

Compile time unit testing is a significant win:

1. it's always more productive to find problems at compile time rather than run time

2. it isn't necessary to conditionally turn off compilation of the tests for the release build

3. you can't forget to run the tests before shipping

What if it was always allowed to do compile time, but you could add a keyword to assert it did (like force-inline).

That way you get benefits by default. Whereas right now it's not allowed to.

These are two completely different things.

One is the provider of the API promising that the function supports compile-time evaluation.

The second is the consumer of the API ensuring that an expression has been compile-time evaluated. It's nice that the consumer can make sure, but that's not helpful if the provider of the API never specifically intended for a function to be evaluatable at compile-time.

> Whereas right now it's not allowed to.

Of course it's allowed, but you're at the mercy of the compiler's decisions.

> Of course it's allowed,

It's not. If you to use a function in a constexpr context then it will complain it needs to be marked as such. So the API creator needs to label every function in case a client wants to use it.

It is decided by the compiler.

Note that I mean at the declaration not the callsite.