Lets say I have:
(please ignore the fact that I am using strncmp in C )
if (!strncmp(some_str, "constant", strlen("constant"))) {}
The strlen can be evaluated at compile time but it can't be eliminated because the function is not constexpr.
One way around would be (accepted only by g ):
constexpr size_t len = strlen("constant");
if (!strncmp(some_str, "constant", len)) {}
but this is harder to read and less practical.
Is there any way to specify constexpr for a part of a statement?
CodePudding user response:
This is fundamentally impossible. Compilers can delay evaluation - do constexpr calculations later, at runtime. But they can't travel back in time. If even a single (evaluated) subexpression is not constexpr, then the whole expression cannot be constexpr.
CodePudding user response:
You have to be in specific case to force constexpr evaluation, std::integral_constant might help:
if (!strncmp(some_str,
"constant",
std::integral_constant<std::size_t, strlen("constant")>()))
{
// ...
}
alias/MACRO might shorten std::integral_constant<std::size_t, strlen("constant")>()
Not sure it is better than your:
constexpr size_t len = strlen("constant");
if (!strncmp(some_str, "constant", len))
{
// ...
}
Note: I assume that strlen is your own constexpr version (as standard one is not constexpr).
