1

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?

sigidagi
  • 864
  • 7
  • 17
  • 6
    what's wrong with your current implementation? It's perfectly clear what is happening, why convolute (IMHO) it? – Nim Oct 12 '11 at 08:44
  • 1
    What kind of "simple" do you have in mind? clearly the code is not simple enough for a beginner to easily understand, while a plain for loop would be. But then again, I am sure a plain for loop came to your mind already but for whatever reasons you chose to do it otherwise. – PlasmaHH Oct 12 '11 at 08:47
  • "Simple" can be in that sense I can reduce size of code and write one line instead of using additional Functor. – sigidagi Oct 12 '11 at 09:04
  • Are you interested only in C++03 or also C++11 features? Lambdas come to mind... – David Rodríguez - dribeas Oct 12 '11 at 09:15
  • At the moment I'm using VS2008 (it do not support C++11) and boost libraries. – sigidagi Oct 12 '11 at 09:19

1 Answers1

2

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); });
Christian Rau
  • 45,360
  • 10
  • 108
  • 185
David Rodríguez - dribeas
  • 204,818
  • 23
  • 294
  • 489