I'm implementing Python's map in C++ (in a more functional way than std::transform
):
#include <iostream>
#include <vector>
#include <functional>
template <typename TypeOut, typename TypeIn>
std::vector<TypeOut> fmap(std::function<TypeOut(const TypeIn&)> func, const std::vector<TypeIn>& vec) {
std::vector<TypeOut> result;
std::transform(vec.begin(), vec.end(),
std::back_inserter(result),
func);
return std::move(result);
}
int main() {
std::vector<int> vec_test;
vec_test.push_back(1);
vec_test.push_back(2);
vec_test.push_back(3);
std::function<int(const int&)> f = [](const int& x) {return x*x;};
auto squared = fmap(f, vec_test);
for (const auto& x: squared) {
std::cout<<x<<" ";
}
std::cout<<std::endl;
return 0;
}
This program is working, but it annoys me to manually set the type for std::function
in:
std::function<int(const int&)> f = [](const int& x) {return x*x;};
How do I make compiler inference the type for me so that I could have
auto f = [](const int& x) {return x*x;};
auto squared = fmap(f, vec_test);
or even simpler:
auto squared = fmap([](const int& x) {return x*x;}, vec_test);