Re:Just how constexpr is C++20’s std:string?
by scatters on Friday September 08, 2023 @09:03PM
(#37441173)
You can use `std::array<char>` (which, as it happens, is a literal type) as an intermediary when performing materialization. A nice toy example is to build a comma-separated string listing enumerators:
template<class E> requires std::is_enum_v<E> constexpr std::string_view joinedEnum() {
constexpr auto generate = [] -> std::string {
return []<template<class...> class L, class... D>(L<D...>) {
std::string str;
(((str += (str.empty() ? "" : ", ")) += D::name), ...);
return str;
}(boost::describe::describe_enumerators<E>());
};
static constexpr auto arr = [&] {
constexpr std::size_t N = generate().size();
std::array<char, N> arr;
std::char_traits<char>::copy(arr.data(), generate().data(), N);
return arr;
}();
return std::string_view(arr);
}
Note that you have to generate the constexpr std::string twice; once for its size, once for its contents. But you assume that the compiler can memoize the result.
If there was reflection, it would be useful to talk about class names, function names, etc, at compile time.