C++ Logo

std-proposals

Advanced search

[std-proposals] [C++ Proposal] Generic compile-time view

From: Omar Dooley <omardooley_at_[hidden]>
Date: Thu, 27 Jun 2024 21:44:49 +0000 (UTC)
/* It's easy to make an array of uniquely sized compile-time strings: */
constinit std::array ct_str_arr { "These"sv, "Are"sv, "Compile-time"sv, "Strings"sv, "Of"sv, "Unique"sv, "Size"sv};void print_strings(void){ for(const auto& str : ct_str_arr) std::print("{} [{}]\n", str, str.size());}
/* This is possible because after all they're just pointers (to an array of chars), * but where is this flexibility for other (trivial[?]) types? std::chrono::duration, * int, float, bool, [user-defined] ... * * Vectors are runtime, and Arrays require a predetermined size; and if given an * array of arrays, all the contained arrays must be the same size... What a * waste that becomes when their intended sizes vary. */
constinitstd::array<std::array<int, 6>, 3> arr {{ { 9, 8 }, // 4 wasted slots { 1, 2, 3, 4 }, // 2 wasted slots { 7, 3, 3, 6, 3, 2 }}};
/* An array of T* is our safest bet but files would be littered with * declarations and we'd need to account for the sizes of each array when * reading. This approach requires a lot of manual management from the user * that could be avoided. */
constinit int arr1[3] { 1, 2, 3 };constinit int arr2[6] { 1, 2, 3, 4, 5, 6 };constinit std::array<int*, 2> arr3 { arr1, arr2 };
/* using an std::initializer_list is very close, but this approach betrays it's * intended use, and not to mention it's undefined behavior and/or ill-formed - * even with (P2752R1) "Static storage for braced initializers" */
using init_list = std::initializer_list<milliseconds>;constinit std::array<init_list, 3> arr { { 32ms, 3ms, 18ms, 123ms }, { 2ms, 86ms }, { 40ms, 12ms, 92ms }};
/* Thus I'm proposing a generic, compile-time view (std::generic_view[?]) for * the added flexibility it provides. It would have the written semantics of a * std::string_view but is not exclusive to char types. * * There should be a simple means of expressing sequences of arbitrary data in * string-like fashion without the size specification constraints of arrays and * the allocation of vector. */
/* Example Use 1 */constinit std::array<std::generic_view<int>, 4> arr { {1, 4, 2, 6, 7}, {9, 3, 6}, {6, 2, 0, 1}, {3, 7}};
/* Example Use 2 */enum class Moves { /* Move names... */ };struct HeroData{ std::string_view name; std::generic_view<Moves> move_pool; std::size_t move_count(void) { return move_pool.size(); }};constinit std::array<HeroData> { { "Jack"sv, { /* Move names... */ } }, { "Fillia"sv, { /* Move names... */ } }, { "Weiss"sv, { /* Move names... */ } }};

Received on 2024-06-27 21:44:56