Wludzik, Jozef | e236279 | 2020-10-27 17:23:55 +0100 | [diff] [blame] | 1 | #pragma once |
| 2 | |
| 3 | #include <algorithm> |
| 4 | #include <iterator> |
| 5 | |
| 6 | namespace utils |
| 7 | { |
| 8 | namespace detail |
| 9 | { |
| 10 | |
| 11 | template <class T> |
Szymon Dompke | 7e114c0 | 2022-10-13 18:15:23 +0200 | [diff] [blame] | 12 | concept has_member_reserve = requires(T t) { t.reserve(size_t{}); }; |
Wludzik, Jozef | e236279 | 2020-10-27 17:23:55 +0100 | [diff] [blame] | 13 | |
Wludzik, Jozef | e236279 | 2020-10-27 17:23:55 +0100 | [diff] [blame] | 14 | } // namespace detail |
| 15 | |
Szymon Dompke | fdb06a1 | 2022-02-11 11:04:44 +0100 | [diff] [blame] | 16 | template <template <class, class...> class R, class Container, class Functor> |
| 17 | inline auto transform(const Container& container, Functor&& f) |
Wludzik, Jozef | e236279 | 2020-10-27 17:23:55 +0100 | [diff] [blame] | 18 | { |
Szymon Dompke | fdb06a1 | 2022-02-11 11:04:44 +0100 | [diff] [blame] | 19 | auto result = R<decltype(f(*container.begin()))>{}; |
Wludzik, Jozef | e236279 | 2020-10-27 17:23:55 +0100 | [diff] [blame] | 20 | |
Krzysztof Grobelny | 60fee07 | 2022-01-13 16:25:04 +0100 | [diff] [blame] | 21 | if constexpr (detail::has_member_reserve<decltype(result)>) |
Wludzik, Jozef | e236279 | 2020-10-27 17:23:55 +0100 | [diff] [blame] | 22 | { |
| 23 | result.reserve(container.size()); |
| 24 | } |
Szymon Dompke | fdb06a1 | 2022-02-11 11:04:44 +0100 | [diff] [blame] | 25 | |
Wludzik, Jozef | e236279 | 2020-10-27 17:23:55 +0100 | [diff] [blame] | 26 | std::transform(container.begin(), container.end(), |
| 27 | std::inserter(result, result.end()), |
Szymon Dompke | fdb06a1 | 2022-02-11 11:04:44 +0100 | [diff] [blame] | 28 | std::forward<Functor>(f)); |
| 29 | |
Wludzik, Jozef | e236279 | 2020-10-27 17:23:55 +0100 | [diff] [blame] | 30 | return result; |
| 31 | } |
| 32 | |
Szymon Dompke | fdb06a1 | 2022-02-11 11:04:44 +0100 | [diff] [blame] | 33 | template <template <class, class...> class Container, class Functor, |
| 34 | class... Args> |
| 35 | inline auto transform(const Container<Args...>& container, Functor&& f) |
Krzysztof Grobelny | 60fee07 | 2022-01-13 16:25:04 +0100 | [diff] [blame] | 36 | { |
Szymon Dompke | fdb06a1 | 2022-02-11 11:04:44 +0100 | [diff] [blame] | 37 | return transform<Container, Container<Args...>, Functor>( |
| 38 | container, std::forward<Functor>(f)); |
Krzysztof Grobelny | 60fee07 | 2022-01-13 16:25:04 +0100 | [diff] [blame] | 39 | } |
| 40 | |
Wludzik, Jozef | e236279 | 2020-10-27 17:23:55 +0100 | [diff] [blame] | 41 | } // namespace utils |