Skip to content

Instantly share code, notes, and snippets.

@rustyx
Last active February 17, 2021 14:58
Show Gist options
  • Save rustyx/0def5c6adf9607536eb5951eb3d95a28 to your computer and use it in GitHub Desktop.
Save rustyx/0def5c6adf9607536eb5951eb3d95a28 to your computer and use it in GitHub Desktop.
C++ make_array
#include <array>
#include <tuple>
#include <utility>
/*
Makes a std::array of objects without a default constructor.
C++17 is required for std::make_from_tuple, otherwise can be adapted for C++14.
Example usage:
struct A {
A(std::string s) {}
};
std::array<A, 12> arr = make_array<A, 12>("abc");
*/
template <typename T, typename ArgT, std::size_t... Is>
constexpr std::array<T, sizeof...(Is)> make_array_impl(ArgT&& argt, std::index_sequence<Is...>) {
return {{(Is, std::make_from_tuple<T>(std::forward<ArgT>(argt)))...}};
}
template <typename T, std::size_t N, typename... Args>
constexpr std::array<T, N> make_array(Args&&... args) {
return make_array_impl<T>(std::make_tuple(std::forward<Args>(args)...), std::make_index_sequence<N>());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment