Few days ago I discovered that you can find compile-time strlen
using something like this:
template<size_t N>
constexpr size_t strlen_(const char (&data)[N]) noexcept{
return N - 1;
}
If it's compiled, then all is good. You can add overload such this:
size_t strlen_(const char *s) noexcept{
return strlen(s);
}
Then it will always compiles.
My question is - does C++ <cstring>
uses something like this and if it does not - why?
No, it doesn't. Because it gives the wrong answer.
char x[10] = "abc";
int correct_length = std::strlen(x); // 3
int incorrect_length = strlen_(x); // 9
Also, with your 2 overloads, the template will never be called. The non-template one accepting a const char*
will always be preferred.
This doesn't mean that strlen can't be calculated at compile time with some compiler magic. But it can't be done this way, using the language proper.
Your strlen_
returns the size of arraydata
, not the size of a null-terminated string. A correct implementation would be:
constexpr size_t ct_strlen( const char* s ) noexcept
{
return *s ? 1 + ct_strlen(s + 1) : 0;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With