functional programming techniques for generating objects on the heap

180 views Asked by At

There is example of code which generates N objects of class A on the heap:

#include <vector>
#include <iostream>
#include <algorithm>
#include <boost/shared_ptr.hpp>
#include <boost/make_shared.hpp>

using boost::make_shared;
using boost::shared_ptr;

class A
{
    int val_;
public:
    explicit A(int i) : val_(i) {}
    int foo() const { return val_;}
};

template<typename T>
struct Generator
{
    shared_ptr<T> operator()()
    {
        return make_shared<T>(std::rand() % 10 + 1);
    }
};


int main()
{
    std::vector< shared_ptr<A> > coll;
    std::generate_n( back_inserter(coll), 3, Generator<A>());

    std::vector<shared_ptr<A> >::const_iterator cit;
    for (cit = coll.begin(); cit != coll.begin(); ++cit)
        std::cout << (*cit)->foo() << std::endl;            

    return 0;
}

Code uses functor "Generator" and "generate_n" algorithm to do the job. I wounder about simplification of this task. boost:lambda, boost::phoenix are possible candidates (if they are?), and how to do it? Or maybe there are other alternatives?

1

There are 1 answers

3
David Rodríguez - dribeas On

Simple would be not to convolute the problem in the first case:

std::vector< std::shared_ptr<A> > ints;
for ( int i = 0; i < 3; ++i ) 
   ints.push_back( std::make_shared<A>( std::rand()%10 + 1 ) );

Each different paradigm has its strengths and weaknesses, and in this case, in C++, trying to force a functional approach to the problem will make things more complex than they need be.

With lambda support in the compiler you could do:

std::vector< shared_ptr<A> > coll;
std::generate_n( back_inserter(coll), 3, [](){ 
    return std::make_shared<A>(std::rand()%10 + 1); });