eVoid Development Weblog Burn The Land And Boil The Sea But You Can't Take The Sky From Me

21Jul/100

C++0x, Lambda Expressions and Visitors

I know there are thousands and millions of articles out there dealing with the new features that are being introduced by the new C++ ISO standard commonly known as C++0x. Today I read that on Code Project and got very enthusiastic about the part that described the lambda expressions. I know that is damn geeky but I almost went bananas :D when I read what they are and what kinda stuff you can do with them. Countless situations came immediately on my mind in which I could take advantage of them. Usually I tend to make very extensive use of the Visitor pattern. Most of my classes that encapsulate some kind of an 1 -to- n>1 association do offer a function like VisitObjects( :UnaryFunction ). I like it that much because I believe it's the most short and abstract way to offer an interface for the traversal of associated objects. No matter how the data is internally organized - whether it's a tree or maybe a flat structure like a linked list or an array - the interface stays all the same. Up to now I had to do the following to make use of that kind of interfaces:

namespace impl
{
 
class MyFunctor
{
public:
 
    int i;
 
    MyFunctor( int i )
        : i( i )
    {
    }
 
    bool operator() ( const MyElement& e )
    {
        std::cout << ( i++ ) << " - " << e << std::endl;
        return true;  //< continue traversal
    }
 
};
 
}  // namespace impl
 
 
void MyClass::MyFunction()
{
    impl::MyFunctor visitor( 0 );
 
    MySet.VisitMyElements( visitor );
 
    std::cout << "We've vistited " << visitor.i << " elements" << std::endl;
}

Everyone will admit that is kinda ugly. Now, thanks to lambda expressions, I could just inline the whole logic into the one really necessary function:

void MyClass::MyFunction()
{
    int i = 0;
    MySet.VisitMyElements( [&]( const MyElement& e )->bool
            {
                std::cout << ( i++ ) << " - " << e << std::endl;
                return true;  //< continue traversal
            } );
 
    std::cout << "We've vistited " << i << " elements" << std::endl;
}

Though I haven't tested it, to me lambda expressions and the visitor pattern seem like made for each other :D

  • Share/Bookmark
Kommentare (0) Trackbacks (0)

Zu diesem Artikel wurden noch keine Kommentare geschrieben.


Kommentar schreiben


Noch keine Trackbacks.