コンパイル時に配列の任意の箇所へ要素を挿入する
コンパイル時に配列の任意の箇所へ要素を挿入し、その結果を新しい配列として返す関数です。
push_at(array, value, position);
によってarrayの中のpositionにvalueを挿入した配列を返します。
同様のテクニックを用いて、配列のある位置に別の配列の要素を挿入した配列を得る関数も簡単に定義出来ると思います。
任意の箇所へ非常に簡単且つ、高速に挿入を行う事が出来ますね。
この定義はC++1y向けです。
C++11では関数の戻り値の型を明示するため -> decltype(関数定義)を追加する必要があります。
#include <type_traits> #include <sprout/array.hpp> #include <sprout/index_tuple.hpp> template<class T, std::size_t size, sprout::index_t... indexes> constexpr auto push_at_impl(const sprout::array<T, size> data, const T I, const std::size_t pos, sprout::index_tuple<indexes...>) { return sprout::array<T, sizeof...(indexes)>{{(indexes != pos ? data[indexes < pos ? indexes : indexes - 1] : I)...}}; } template<class T, std::size_t size> constexpr auto push_at(const sprout::array<T, size> data, const T I, const std::size_t pos) { return push_at_impl(data, I, pos, typename sprout::index_range<0, size + 1>::type()); } int main() { constexpr auto array1 = sprout::make_array<int>(0, 1, 2, 3, 4); constexpr auto array2 = push_at(array1, 5, 0); constexpr auto array3 = push_at(array1, 10, 5); constexpr auto array4 = push_at(array1, 100, 3); static_assert(array2 == sprout::make_array<int>(5, 0, 1, 2, 3, 4), ""); static_assert(array3 == sprout::make_array<int>(0, 1, 2, 3, 4, 10), ""); static_assert(array4 == sprout::make_array<int>(0, 1, 2, 100, 3, 4), ""); }