Last active
February 17, 2021 14:58
-
-
Save rustyx/0def5c6adf9607536eb5951eb3d95a28 to your computer and use it in GitHub Desktop.
C++ make_array
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 <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