Use compile-time vectors and strings with constexpr
C++20 allows the use of constexpr
in several new contexts. This provides improved efficiency, in that these things may be evaluated at compile time, instead of run time.
How to do it…
The specification includes the ability to use string
and vector
objects in constexpr
context. It's important to note that these objects may not themselves be declared constexpr
, but they may be used in a compile-time context:
constexpr auto use_string() { string str{"string"}; return str.size(); }
You can also use algorithms in constexpr
context:
constexpr auto use_vector() { vector<int> vec{ 1, 2, 3, 4, 5}; return accumulate(begin(vec), end(vec), 0); }
The result of the accumulate
algorithm is available at compile time and in constexpr
context.
How it works…
The constexpr
specifier declares...