Hacker News new | ask | show | jobs
by pjmlp 1521 days ago
It is compile time, so the expectation is that the compiler replaces it anyway, although you might be right.
1 comments

`constexpr` isn't "compile time". It's potentially compile time at best. Debug builds in particular will go out of their way to evaluate things at runtime, presumably so you can set breakpoints and step through code, even when it's completely pointless. I have seen the following function show up in a profiler:

    template < bool value >
    bool constexpr IsEnabled() { return value; }
This was used to silence warnings about unconditional branches in a macro. There are ways to force such functions to be evaluated at compile time, but they're pretty awkward, and limited to integral types (you can't use them on string_view s):

    #define EVAL_AT_COMPILE_TIME(x) std::integral_constant<decltype(x), x>::value
    const bool x = EVAL_AT_COMPILE_TIME(IsEnabled<true>());
> There are ways to force such functions to be evaluated at compile time, but they're pretty awkward

C++20 has “consteval“: https://en.cppreference.com/w/cpp/language/consteval

That is why main() has a static constexpr, to force its execution at compile time. A trick I learned from Jason's screencasts.

Although, you're right. I tried it back at home on VC++ and its static analyser wasn't happy.

My idea was to make use of template metaprogramming to generate the string buffer, there are a couple of examples of such attempts.

However, I guess with such amount of additional code, I should declare defeat on the original comment.

Seems to me the good news is that your compiler told you this doesn't work.

In languages where you can't tell the compiler you think this is constant, there's a risk you delude yourself, especially because computers are very fast, and you think you've got O(1) when it's actually O(N) or even O(N^2) and one day N gets big enough and you're in real trouble.

Yeah, because I am one of those persons that when I use languages like C and C++, and have the last word, the seatbelt and metal gloves are always turned on.

Those examples for HN recreation naturally weren't written with such care.