Reputation: 24805
C++ with its new features seems to be a new language for those who write old fashion codes. Consider this function
template<typename Type>
void Sequitur<Type>::printList(const Symbol * list, unsigned int number) const
{
list->forUntil([&number, this](const Symbol * item) {
if(typeid(*item) == ValueType) {
fout << static_cast<const Value*>(item)->getValue() << " ";
}
if(!--number)
return false;
else
return true;
});
}
This inline function is defined in a so called tpp
file
template<typename Child>
template<typename Function> const Child * BaseList<Child>::forUntil(const Function & f) const
{
const BaseList * item = this;
const BaseList * next;
while(item) {
next = item->next_ptr;
if(!f(static_cast<const Child*>(item)))
break;
item = next;
}
return static_cast<const Child*>(item);
}
Assume everything is defined since the code is working. What I want to do is to add a counter to count how many time the while
is executed. The counter value should be available at the end of printList()
.
How can I accomplish that?
Upvotes: 0
Views: 33
Reputation: 19148
This has not much to do with lambdas. If you'd like to get the number of iterations, instead of overly complicating your code, change the return type of forUntil
to std::pair<const Child*, std::size_t>
, where retval.second
is the iteration count.
On the other hand, if you need how many times the functor has been called, you can track it yourself:
template<typename Type>
void Sequitur<Type>::printList(const Symbol * list, unsigned int number) const
{
std::size_t fCallNum = 0;
list->forUntil([&](const Symbol * item) {
++fCallNum;
if(typeid(*item) == ValueType) {
fout << static_cast<const Value*>(item)->getValue() << " ";
}
if(!--number)
return false;
else
return true;
});
std::cout << "Functor called " << fCallNum << " times\n";
}
In your particular case, these the two counters would result in the same value, however, they are semantically different.
Upvotes: 2