Skip to content

Instantly share code, notes, and snippets.

@rr-codes
Last active May 13, 2020 08:54
Show Gist options
  • Save rr-codes/f8a845af530e13f026353eb5a17f6e85 to your computer and use it in GitHub Desktop.
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)
#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