Equivalent of python map function using lambda
Baum mit Augen's answer is most of the way there. Just takes a few more steps to support anything that is for-each-able:
template <typename C, typename F>
auto apply(C&& container, F&& func)
{
using std::begin;
using std::end;
using E = std::decay_t<decltype(std::forward<F>(func)(
*begin(std::forward<C>(container))))>;
std::vector<E> result;
auto first = begin(std::forward<C>(container));
auto last = end(std::forward<C>(container));
result.reserve(std::distance(first, last));
for (; first != last; ++first) {
result.push_back(std::forward<F>(func)(*first));
}
return result;
}
We can even go one step further and make this SFINAE-able by not using C++14 auto
deduction and instead moving the failure up to the deduction phase. Start with a helper for begin
/end
:
namespace adl_helper {
using std::begin;
using std::end;
template <typename C>
auto adl_begin(C&& c) -> decltype(begin(std::forward<C>(c))) {
return begin(std::forward<C>(c));
}
template <typename C>
auto adl_end(C&& c) -> decltype(end(std::forward<C>(c))) {
return end(std::forward<C>(c));
}
}
using adl_helper::adl_begin;
using adl_helper::adl_end;
And then use that to deduce E
earlier:
using adl_helper::adl_begin;
using adl_helper::adl_end;
template <typename C,
typename F,
typename E = std::decay_t<decltype(std::declval<F>()(
*adl_begin(std::declval<C>())
))>
>
std::vector<E> apply(C&& container, F&& func)
{
/* mostly same as before, except using adl_begin/end instead
of unqualified begin/end with using
*/
}
Now we can test at compile time if some container/function pair is apply
-able, and the error is a deduction failure instead of a usage failre:
int arr[] = {1, 2, 3};
auto x = apply(arr, []{ return 'A'; });
main.cpp: In function 'int main()':
main.cpp:45:52: error: no matching function for call to 'apply(int [3], main()::<lambda()>)'
auto x = apply(arr, []() -> char { return 'A'; });
^
main.cpp:29:16: note: candidate: template<class C, class F, class E> std::vector<E> apply(C&&, F&&)
std::vector<E> apply(C&& container, F&& func)
^
main.cpp:29:16: note: template argument deduction/substitution failed:
main.cpp:25:50: error: no match for call to '(main()::<lambda()>) (int&)'
typename E = decltype(std::declval<F>()(
^
As pointed out, this would not handle a container of input iterators well. So let's fix it. We need something to determine the size of the container. If the container has a size()
member function, we can use that. Otherwise if the iterators do not have category input_iterator_tag
(don't know of any other way to distinguish input iterators...), we can use that. Otherwise, we're kind of out of luck. A good way of doing decreasing order of preference like this is to introduce a chooser
hierarchy:
namespace details {
template <int I> struct chooser : chooser<I-1> { };
template <> struct chooser<0> { };
}
And then just walk down:
namespace details {
template <typename C>
auto size(C& container, chooser<2>) -> decltype(container.size(), void())
{
return container.size();
}
template <typename C,
typename It = decltype(adl_begin(std::declval<C&>()))
>
auto size(C& container, chooser<1>)
-> std::enable_if_t<
!std::is_same<std::input_iterator_tag,
typename std::iterator_traits<It>::iterator_category
>::value,
size_t>
{
return std::distance(adl_begin(container), adl_end(container));
}
template <typename C>
size_t size(C& container, chooser<0>)
{
return 1; // well, we have no idea
}
}
template <typename C>
size_t size(C& container)
{
return size(container, details::chooser<10>{});
}
Then we can use size()
to reserve()
our vector to the best of our ability:
template <typename C,
typename F,
typename E = std::decay_t<decltype(std::declval<F>()(
*adl_begin(std::declval<C>())
))>
>
std::vector<E> apply(C&& container, F&& func)
{
std::vector<E> result;
result.reserve(size(container));
for (auto&& elem : container) {
result.push_back(std::forward<F>(func)(std::forward<decltype(elem)>(elem)));
}
return result;
}
This can certainly be done and would probably look something like this:
template <class Container, class Function>
auto apply (const Container &cont, Function fun) {
std::vector< typename
std::result_of<Function(const typename Container::value_type&)>::type> ret;
ret.reserve(cont.size());
for (const auto &v : cont) {
ret.push_back(fun(v));
}
return ret;
}
If you want to be super general and handle C arrays and everything, you might need to add a couple of overloads for the special cases.
Live example
This works with your example, and with most of the containers. I use std::transform, because it can be optimized for each stl iterator. I started out from Baum mit Augen's answer, which was deleted later.
template<typename Container, typename Function>
using _mapT = std::vector<typename std::result_of<Function(const typename Container::value_type&)>::type>;
template <typename Container, typename Function>
_mapT<Container, Function> map(const Container &container, Function &&f)
{
_mapT<Container, Function> ret; ret.reserve(container.size());
std::transform(container.begin(), container.end(), std::back_inserter(ret), std::forward<Function>(f));
return ret;
}