Monday, March 12, 2012

Practice on C++11(2): tuple, rvalue, auto, lambda

Continue with my previous post about rvalue, auto, lambda, decltype, My second practice is to create a list of objects without knowing too much details. I'll give also 2 styles of code for comparing:

1. Traditional C++ style:

[cpp]
// definition of getTaskList:
// void getTaskLists( std::vector<int>& ids, std::vector<QString>& names );
std::vector<int> ids;
std::vector<QString> names;
PDatabaseManager::instance()->getTaskLists( ids, names );
Q_ASSERT( ids.size() == names.size() );

PLists lists;
for( size_t i = 0; i < ids.size(); ++i )
{
lists.push_back( PListPtr( new PListSqlite( ids[i], names[i] ) ) );
}
[/cpp]


2. C++11 style, also, leverage algorithms instead of write code by yourself:

[cpp]
// definition of getTaskList:
// std::vector< std::tuple<int, QString> > getTaskLists();
auto&& rawlists = PDatabaseManager::instance()->getTaskLists();

PLists lists;
std::for_each( rawlists.begin(), rawlists.end(), [&]( const std::tuple<int, QString>& i ) {
lists.push_back( PListPtr( new PListSqlite( std::get<0>( i ), std::get<1>( i ) ) ) );
} );
[/cpp]


The new style looks more elegant and clean.

No comments:

Post a Comment