Hacker News new | ask | show | jobs
by scatters 1007 days ago
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.