Monday, March 12, 2012

Practice on C++11(1): rvalue, auto, lambda, decltype

I learned C++ programming language when I was a sophomore in the year 1998, and I started to use C++ on commercial software since 2001. I'm insist in using C++ for most of my projects just because I'm a skilled programmer. I have ever read books for C++98, and articles/presentations/papers for C++0x, but never really used it on my project. Recently I watched the keynotes of Bjarne Stroustrup and Herb Sutter on GoingNative 2012, I was motivated change my mind from traditional C++ mindset to C++11. The project of company still using Visual Studio 2008 as the compiler, I practiced C++11 on a side project in my spare time.

Here is my first practice which leveraged: rvalue, auto, lambda, decltype:

This function is in my unit test, the purpose is to check if there a line in the canvas with specified start and end point.

1. Traditional Style(not compiled, just write here for comparing with C++11 style)
[cpp]
bool hasLine( const QPointF& start, const QPointF& end )
{
std::vector<DGraphicsItem*> items = canvas.items();
for( std::vector<DGraphicsItem*>::const_iterator i = items.constBegin();
i != items.constEnd(); ++i )
{
DGraphicsItemLine* pLine = dynamic_cast<DGraphicsItemLine*>( p );
if ( !pLine ) continue;
if ( pLine-->startPoint() == start && pLine-->endPoint() == end ) return true;
}
return false;
}
[/cpp]

2. C++11 style
[cpp]
bool hasLine( const QPointF& start, const QPointF& end )
{
auto&& items = canvas.items();
return std::find_if( items.constBegin(), items.constEnd(),
[&]( DGraphicsItem* p ) -> bool
{
auto pLine = dynamic_cast<decltype(m_pLine)>( p );
return pLine && pLine->startPoint() == start && pLine->endPoint() == end;
} ) != items.constEnd();
}
[/cpp]

I like the new features in C++11 very much, and it's very impressive for me that my first C++11 style code works gracefully!
You may wonder why I use decltype here. The reason is, when I write other test cases, I may copy the code and make some modifications, if I have the type DGraphicsItemLine here, it's easy for me to miss changing the type. Furthermore, I hope I can get some templates or abstraction so that I can reuse the code in future.

2 comments:

  1. [...] with my previous post about rvalue, auto, lambda, decltype, My second practice is to create a list of objects without [...]

    ReplyDelete