QAbstractItemModel foreach iterator with functors: is there a better way to do this?

I am editing a simple QDomModel example to add some meat for my application, and I need to clear some status flags that I added sometimes. Iterating through the elements of the QAbstractItem model is annoying because a standard iterator is not provided, so I wrote my own for_each style function to iterate over each element and execute the "f" function on it.

template<typename Functor> void foreach_item(Functor f, QModelIndex &parent = QModelIndex()) { if (!parent.isValid()) parent = index(0,0,QModelIndex()); int numRows = rowCount(parent); for (int i=0; i<numRows; i++) { foreach_item(f,index(i,0,parent)); } f(parent); } 

This works, and I can give it all kinds of big lambdas or functors and call it like this:

 void QDomModel::clearChanges() { foreach_item([&](QModelIndex parent) { QDomItem* item = static_cast<QDomItem*>(parent.internalPointer()); item->valueChanged = false; }); changeCount = 0; } 

This is very powerful, but the problem that I encountered is that if you do not dig into the code, you can not imagine what the signature of the functor / lambda is. You get a compilation error if you give it something wrong, but I'm worried that it might be a bad interface (or even the wrong coding practice) for creating these types of functions.

Is it better to accept function pointers when accepting arguments for clarity? Are there any consequences or limitations to doing one way against another that I should be aware of?

+5
source share
1 answer

std::function will allow you to specify the type in the signature. Try something like:

 void foreach_item(const std::function<void(const QModelIndex&)> &f, QModelIndex parent = QModelIndex()) { /*...*/ } 
+2
source

Source: https://habr.com/ru/post/1203406/


All Articles