2

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?

1 Answer 1

2

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

1
  • 2
    Your answer gave me a clue, and I realized we should be using czstring_span instead and then we don't have the problem. The other issue is that MSVC doesn't really handle complex constexpr things very well. This is where its C++17 support is the most lacking. gcc and clang are fully capable of handling removing the terminating null in a constexpr way. Sep 21, 2018 at 22:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.