Last active
May 13, 2020 08:54
-
-
Save rr-codes/f8a845af530e13f026353eb5a17f6e85 to your computer and use it in GitHub Desktop.
A proof of concept C++20 type-safe variadic argument array creation function (using C++20 Concepts and Variadic Templates)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <array> | |
#include <iostream> | |
template<typename ...Args> | |
constexpr std::size_t ARG_SIZE() { return sizeof...(Args) + 1; } | |
template<typename From, typename To> | |
concept SameAs = std::is_same_v<From, To>; | |
template<std::size_t N, typename T, SameAs<T>... Ts> | |
constexpr void set(std::array<T, N>& arr, T arg, Ts... args) | |
{ | |
static_assert(ARG_SIZE<Ts...>() <= N, "size of args exceeds size of array"); | |
constexpr std::size_t Idx = N - ARG_SIZE<Ts...>(); | |
arr[Idx] = arg; | |
if constexpr (Idx < N - 1) { | |
set(arr, args...); | |
} | |
} | |
template<typename T, SameAs<T>... Ts> | |
constexpr std::array<T, ARG_SIZE<Ts...>()> arrayOf(T first, Ts... elements) | |
{ | |
auto tmp = std::array<T, ARG_SIZE<Ts...>()>(); | |
set(tmp, first, elements...); | |
return tmp; | |
} | |
int main() { | |
auto a1 = arrayOf(1, 2, 3); // ok | |
auto a2 = arrayOf(1, "a", "b"); // fails requirements | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment