Date: Thu, 3 Jul 2025 20:30:52 -0400
I want to convert over a large codebase away from C-style strings. One of
the sticking points is compile-time string constants.
Modern C++ practice is to use `constexpr std::string_view`. However, I
cannot easily use that string_view in an interface that accepts
null-terminated C-style strings. This makes it difficult to do an
incremental migration.
I currently have two options:
1. I can manually add a null-terminator if I want to pass a string_view
into a function expecting C-style strings. This is confusing and violates
the intended usage of string_view.
2. I can create my own wrapper of std::string_view that guarantees
null-termination. However, this isn't idiomatic and project-specific.
Instead, I propose to add a `consteval c_str()` function that constructs a
C-string from a string_view at compile-time. This wouldn't be a good idea
at runtime (so it can't be `constexpr`) because it would trigger a memory
allocation on an object that's supposed to be a non-owning reference.
However, I don't see any issues with this at compile-time, since the
compiler can figure out what the string_view should look like.
What does std-proposals think? Should I write an actual draft?
the sticking points is compile-time string constants.
Modern C++ practice is to use `constexpr std::string_view`. However, I
cannot easily use that string_view in an interface that accepts
null-terminated C-style strings. This makes it difficult to do an
incremental migration.
I currently have two options:
1. I can manually add a null-terminator if I want to pass a string_view
into a function expecting C-style strings. This is confusing and violates
the intended usage of string_view.
2. I can create my own wrapper of std::string_view that guarantees
null-termination. However, this isn't idiomatic and project-specific.
Instead, I propose to add a `consteval c_str()` function that constructs a
C-string from a string_view at compile-time. This wouldn't be a good idea
at runtime (so it can't be `constexpr`) because it would trigger a memory
allocation on an object that's supposed to be a non-owning reference.
However, I don't see any issues with this at compile-time, since the
compiler can figure out what the string_view should look like.
What does std-proposals think? Should I write an actual draft?
Received on 2025-07-04 00:31:04