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> |
Krzysztof Grobelny | 60fee07 | 2022-01-13 16:25:04 +0100 | [diff] [blame^] | 12 | concept has_member_reserve = requires(T t) |
Wludzik, Jozef | e236279 | 2020-10-27 17:23:55 +0100 | [diff] [blame] | 13 | { |
Krzysztof Grobelny | 60fee07 | 2022-01-13 16:25:04 +0100 | [diff] [blame^] | 14 | t.reserve(size_t{}); |
Wludzik, Jozef | e236279 | 2020-10-27 17:23:55 +0100 | [diff] [blame] | 15 | }; |
| 16 | |
Wludzik, Jozef | e236279 | 2020-10-27 17:23:55 +0100 | [diff] [blame] | 17 | } // namespace detail |
| 18 | |
Krzysztof Grobelny | 60fee07 | 2022-01-13 16:25:04 +0100 | [diff] [blame^] | 19 | template <class R, class Container, class F> |
| 20 | auto transform(const Container& container, F&& functor) |
Wludzik, Jozef | e236279 | 2020-10-27 17:23:55 +0100 | [diff] [blame] | 21 | { |
Krzysztof Grobelny | 60fee07 | 2022-01-13 16:25:04 +0100 | [diff] [blame^] | 22 | auto result = R{}; |
Wludzik, Jozef | e236279 | 2020-10-27 17:23:55 +0100 | [diff] [blame] | 23 | |
Krzysztof Grobelny | 60fee07 | 2022-01-13 16:25:04 +0100 | [diff] [blame^] | 24 | if constexpr (detail::has_member_reserve<decltype(result)>) |
Wludzik, Jozef | e236279 | 2020-10-27 17:23:55 +0100 | [diff] [blame] | 25 | { |
| 26 | result.reserve(container.size()); |
| 27 | } |
| 28 | std::transform(container.begin(), container.end(), |
| 29 | std::inserter(result, result.end()), |
| 30 | std::forward<F>(functor)); |
| 31 | return result; |
| 32 | } |
| 33 | |
Krzysztof Grobelny | 60fee07 | 2022-01-13 16:25:04 +0100 | [diff] [blame^] | 34 | template <template <class, class...> class Container, class T, class... Args, |
| 35 | class F> |
| 36 | auto transform(const Container<T, Args...>& container, F&& functor) |
| 37 | { |
| 38 | using R = Container<decltype(functor(*container.begin()))>; |
| 39 | return transform<R>(container, std::forward<F>(functor)); |
| 40 | } |
| 41 | |
Wludzik, Jozef | e236279 | 2020-10-27 17:23:55 +0100 | [diff] [blame] | 42 | } // namespace utils |