Search code examples
c++cpp-core-guidelinesms-gsl

Doesn't gsl::cstring_span support constexpr? If not, why should I use it?


I have a piece of code that looks like this:

constexpr gsl::cstring_span<> const somestring{"Hello, I am a string"};

and it refuses to compile with a message complaining that some non-constexpr function is being called somewhere.

Why is this? This seems like the most important use-case to support. The whole point is to have compile-time bounds checking if at all possible. Compile time bounds checking involving constant string literals seems like the thing it would be used for the most often. But this can't happen if it can't be declared constexpr. What's going on here?


Solution

  • I think the problem is that string literals have type array of const char and are null-terminated. But who is to say you are constructing your cstring_span from a null-terminated array?

    Because of that the constructor of cstring_span does a physical check to remove the null terminator if it exists, otherwise accept the full length of the array.

    I am not sure how powerful constexpr expressions can be but it may be possibly to implement it in a constexpr way. You could create an issue asking about it here:

    https://github.com/Microsoft/GSL/issues