blob: fc52fc3783017936cc50d5b3969139f29ac7eb0e [file] [log] [blame]
Wludzik, Jozefe2362792020-10-27 17:23:55 +01001#pragma once
2
3#include <algorithm>
4#include <iterator>
5
6namespace utils
7{
8namespace detail
9{
10
11template <class T>
Krzysztof Grobelny60fee072022-01-13 16:25:04 +010012concept has_member_reserve = requires(T t)
Wludzik, Jozefe2362792020-10-27 17:23:55 +010013{
Krzysztof Grobelny60fee072022-01-13 16:25:04 +010014 t.reserve(size_t{});
Wludzik, Jozefe2362792020-10-27 17:23:55 +010015};
16
Wludzik, Jozefe2362792020-10-27 17:23:55 +010017} // namespace detail
18
Szymon Dompkefdb06a12022-02-11 11:04:44 +010019template <template <class, class...> class R, class Container, class Functor>
20inline auto transform(const Container& container, Functor&& f)
Wludzik, Jozefe2362792020-10-27 17:23:55 +010021{
Szymon Dompkefdb06a12022-02-11 11:04:44 +010022 auto result = R<decltype(f(*container.begin()))>{};
Wludzik, Jozefe2362792020-10-27 17:23:55 +010023
Krzysztof Grobelny60fee072022-01-13 16:25:04 +010024 if constexpr (detail::has_member_reserve<decltype(result)>)
Wludzik, Jozefe2362792020-10-27 17:23:55 +010025 {
26 result.reserve(container.size());
27 }
Szymon Dompkefdb06a12022-02-11 11:04:44 +010028
Wludzik, Jozefe2362792020-10-27 17:23:55 +010029 std::transform(container.begin(), container.end(),
30 std::inserter(result, result.end()),
Szymon Dompkefdb06a12022-02-11 11:04:44 +010031 std::forward<Functor>(f));
32
Wludzik, Jozefe2362792020-10-27 17:23:55 +010033 return result;
34}
35
Szymon Dompkefdb06a12022-02-11 11:04:44 +010036template <template <class, class...> class Container, class Functor,
37 class... Args>
38inline auto transform(const Container<Args...>& container, Functor&& f)
Krzysztof Grobelny60fee072022-01-13 16:25:04 +010039{
Szymon Dompkefdb06a12022-02-11 11:04:44 +010040 return transform<Container, Container<Args...>, Functor>(
41 container, std::forward<Functor>(f));
Krzysztof Grobelny60fee072022-01-13 16:25:04 +010042}
43
Wludzik, Jozefe2362792020-10-27 17:23:55 +010044} // namespace utils