Is it possible to use std::string in a constexpr?

As of C++20, yes, but only if the std::string is destroyed by the end of constant evaluation. So while your example will still not compile, something like this will:

constexpr std::size_t n = std::string("hello, world").size();

However, as of C++17, you can use string_view:

constexpr std::string_view sv = "hello, world";

A string_view is a string-like object that acts as an immutable, non-owning reference to any sequence of char objects.

Leave a Comment