Commit 11e1b8ad authored by Yedidya Feldblum's avatar Yedidya Feldblum Committed by Facebook Github Bot

make_array_with, for making std::array given size and item ctor

Summary: [Folly] `make_array_with`, for making `std::array` given size and item ctor

Reviewed By: ot

Differential Revision: D6831280

fbshipit-source-id: 448bbf4843ffa70324f1a1d2d9e2790dc296548d
parent 28962b90
...@@ -15,11 +15,14 @@ ...@@ -15,11 +15,14 @@
*/ */
#pragma once #pragma once
#include <folly/Traits.h>
#include <array> #include <array>
#include <type_traits> #include <type_traits>
#include <utility> #include <utility>
#include <folly/CPortability.h>
#include <folly/Traits.h>
#include <folly/Utility.h>
namespace folly { namespace folly {
namespace array_detail { namespace array_detail {
...@@ -56,4 +59,21 @@ constexpr array_detail::return_type<D, TList...> make_array(TList&&... t) { ...@@ -56,4 +59,21 @@ constexpr array_detail::return_type<D, TList...> make_array(TList&&... t) {
return {{static_cast<value_type>(std::forward<TList>(t))...}}; return {{static_cast<value_type>(std::forward<TList>(t))...}};
} }
namespace array_detail {
template <typename MakeItem, std::size_t... Index>
FOLLY_ALWAYS_INLINE FOLLY_ATTR_VISIBILITY_HIDDEN constexpr auto make_array_with(
MakeItem const& make,
index_sequence<Index...>) {
return std::array<decltype(make(0)), sizeof...(Index)>{{make(Index)...}};
}
} // namespace array_detail
// make_array_with
//
// Constructs a std::array<..., Size> with elements m(i) for i in [0, Size).
template <std::size_t Size, typename MakeItem>
constexpr auto make_array_with(MakeItem const& make) {
return array_detail::make_array_with(make, make_index_sequence<Size>{});
};
} // namespace folly } // namespace folly
...@@ -69,3 +69,17 @@ TEST(make_array, deduced_common_type) { ...@@ -69,3 +69,17 @@ TEST(make_array, deduced_common_type) {
"Wrong array type"); "Wrong array type");
EXPECT_EQ(arr.size(), 5); EXPECT_EQ(arr.size(), 5);
} }
TEST(make_array_with, example) {
struct make_item {
constexpr int operator()(size_t index) const {
return index + 4;
}
};
using folly::make_array_with;
using folly::array_detail::make_array_with; // should not collide
constexpr auto actual = make_array_with<3>(make_item{});
constexpr auto expected = make_array<int>(4, 5, 6);
EXPECT_EQ(expected, actual);
}
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment