My goal was to have a template function that would take as an input a std::vector of input objects and a function object. This template function would then turn the input vector into a std::vector of converted objects by using the function object and a threadpool.
Example code included below.
I would really like to be able to use a shorter syntax than first creating a local function object, and then passing on all the template parameters.
Compile with gcc: g++ -std=C++0x bla.cpp
#include <vector>
#include <functional>
#include <iostream>
// SYNTAX:
// vector<ResultType> transformed = multiTransform(const vector<InputType>, Transform t)
// where Transform t takes a single InputType as an argument
// ConvertedType has to be default constructible
template <class ConvertedType, class InputType, class Transform>
std::vector<ConvertedType> multiTransform(const std::vector<InputType>& inputs, Transform t) {
std::vector<ConvertedType> results(inputs.size());
{
// boost::threadpool::pool pool(boost::thread::hardware_concurrency());
for(auto it = inputs.begin(); it != inputs.end(); ++it){
auto inputDereferenced = *it;
auto functor = [&, it, inputDereferenced](){
auto result = t(inputDereferenced);
results[it - inputs.begin()] = std::move(result);
};
// pool.schedule(functor);
functor();
}
}
return results;
}
int main() {
std::vector<int> input = {1,2,3};
// auto output = multiTransform(input, [](int a){return float(a);}); // does not compile
auto lambda = [](int a){return a/2.0;};
auto output = multiTransform<float, int, decltype(lambda)>(input, lambda);
for(auto it : output){
std::cout << it << std::endl;
}
}
This works for me with g++ 4.6.3:
You can also make your template declaration a bit more sophisticated:
then you can use