1. 7
  1.  

  2. 2

    Eh, why is strlen not constexpr?

    1. 2

      It’s a C function and often C++ avoids adding extra qualifications to these.

      There’s another variant of this that I’ve used. If you have a template class where the template parameter is the size of a char array then you can return the length via a static method or cosntexpr field. You can use a deduction guide to generate the right instantiations given a string literal. This is probably overkill for this use, but you need such a thing if you want to use strings as template arguments in C++20 (string literals are pointers and so can’t be used, but a class containing a char array can) and if you have one anyway (I wish the standard library provided one, it’s under 10 lines of code, it’s just annoying to have to add it to every project) then you can use it in this context. This version has the benefit that you get a compile failure if you can’t deduce the length at compile time, whereas the constexpr call will fall back to run-time evaluation.

      1. 1

        Because strlen is from the C library, and C doesn’t have constexpr.

        1. 1

          This is not an answer. __cplusplus exists for a reason.

          1. 2

            I’m not sure what you’re getting at. “__cplusplus” doesn’t exist in C, and so it can’t help at all.

            It’s clunky, but that’s how it is.

            1. 1

              There is such thing as #ifdef. __cplusplus is not defined in C and defined in C++, so you can conditionally declare strlen to be constexpr only in C++ and not in C.

              1. 1

                __cplusplus is not defined in C

                But “strlen” is defined in C, and that’s why it can’t be changed. The C++ standards body can’t change C any more than it can change Rust, Posix, or glibc.

                1. 2

                  Sure, but strlen can be unchanged in C and can be constexpr in C++. That doesn’t involve any change to C standard.

                  1. 1

                    They can change std::strlen, though, and this kind of difference isn’t unprecedented, std::isinf (C++) is a set of overloaded functions, whereas isinf (C) is a macro.

        2. 1

          Why not sizeof(string) - 1?