C++20 will add constexpr
strings and vectors
The following proposal has been accepted apparently: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2018/p0980r0.pdf and it adds constructors such as:
// 20.3.2.2, construct/copy/destroy
constexpr
basic_string() noexcept(noexcept(Allocator())) : basic_string(Allocator()) { }
constexpr
explicit basic_string(const Allocator& a) noexcept;
constexpr
basic_string(const basic_string& str);
constexpr
basic_string(basic_string&& str) noexcept;
in addition to constexpr versions of all / most methods.
There is no support as of GCC 9.1.0, the following fails to compile:
#include <string>
int main() {
constexpr std::string s("abc");
}
with:
g++-9 -std=c++2a main.cpp
with error:
error: the type ‘const string’ {aka ‘const std::__cxx11::basic_string<char>’} of ‘constexpr’ variable ‘s’ is not literal
std::vector
discussed at: Cannot create constexpr std::vector
Tested in Ubuntu 19.04.
std::string
is not a literal type – Piotr Skotnicki Nov 25 '14 at 9:47std::string
to be constexpr? there are several compile-time string implementations on SO. what is the point in asking if you can make a non-literal type constexpr if you understand error message and know only literal types can be made constexpr? as well there are several reasons why one may want to have a constexpr instance, so I suggest you clarify your question – Piotr Skotnicki Nov 25 '14 at 10:25constexpr
string implementations out there.std::string
is not one of them. – tenfour Nov 25 '14 at 11:12