Search code examples
c++boostshared-ptrsmart-pointers

Boost smart pointers: Can I express it in a more concise way?


today I've been working with Boost::shared_ptr, and I have a question.

vector<shared_ptr<KlasaA> > vec;
vec.push_back(shared_ptr<KlasaA>(new KlasaB));
vec.push_back(shared_ptr<KlasaA>(new KlasaC));
vec.push_back(shared_ptr<KlasaA>(new KlasaC));
vec.push_back(shared_ptr<KlasaA>(new KlasaA));

for (vector<shared_ptr<KlasaA> >::const_iterator c_it = vec.begin();
    c_it != vec.end(); ++c_it)
{
    cout << c_it->get()->foo(10) << endl;
}

The loop above goes through a vector and polymorphically invokes foo(10).

My question is:

Can...

for (vector<shared_ptr<KlasaA> >::const_iterator c_it = vec.begin();
    c_it != vec.end(); ++c_it)

and

cout << c_it->get()->foo(10) << endl;

be expressed in a more concise way? Thanks in advance.


Solution

  • You could use Boost.Foreach library. Then it will look pretty concise and clear:

    BOOST_FOREACH( boost::shared_ptr<KlasaA> v, vec )
    {
        std::cout << v->foo(10) << std::endl;
    }