Can std::string Be Embodied in a Constant Expression?
In C 11, utilizing std::string within a constant expression poses challenges. However, C 20 provides a solution, albeit with the caveat that the std::string must be destructed before constant evaluation concludes.
C 20 Solution:
While the code snippet you provided will not compile, the following code will:
constexpr std::size_t n = std::string("hello, world").size();
C 17 Alternative: string_view
As an alternative, C 17 introduces string_view, a lightweight string-like object that serves as a non-owning reference to a sequence of char objects. Unlike std::string, string_view is immutable and does not require destruction. This makes it ideal for use in constant expressions:
constexpr std::string_view sv = "hello, world";
The above is the detailed content of Can std::string Be Used in a Constant Expression in C ?. For more information, please follow other related articles on the PHP Chinese website!