- 01
- 02
- 03
- 04
- 05
- 06
- 07
- 08
- 09
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
#include <iostream>
#include <type_traits>
#include <utility>
#include <array>
template<size_t Size, typename T, typename FunctorType, size_t... idx>
constexpr std::array<decltype(std::declval<FunctorType>().operator()(std::declval<T>())), Size>
map_impl(const std::array<T, Size> & arr, FunctorType && f, std::index_sequence<idx...>)
{
return std::array{ f(std::get<idx>(arr))... };
}
template<size_t Size, typename T, typename FunctorType>
constexpr std::array<decltype(std::declval<FunctorType>().operator()(std::declval<T>())), Size>
map(const std::array<T, Size> & arr, FunctorType && f)
{
return map_impl(arr, f, std::make_index_sequence<Size>{});
}
struct MyFunctor {
constexpr float operator()(int arg)
{
return static_cast<float>(arg * arg) / 2.0f;
}
};
int main()
{
constexpr std::array arr{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
auto arrMappedFunctor = map(arr, MyFunctor{});
auto arrMappedLambda = map(arr, [](int x) constexpr { return static_cast<float>(x * x) / 2.0f; });
for (auto && x : arrMappedFunctor) {
std::cout << x << ' ';
}
std::cout << std::endl;
for (auto && x : arrMappedLambda ) {
std::cout << x << ' ';
}
std::cout << std::endl;
return 0;
}