I want to pass a struct implementing operator()
in to a function that accepts boost::function
. This struct keeps track of the number of times it's been called.
struct CallCounter
{
CallCounter() : count( 0 ) {}
void operator()()
{
// do stuff
cout << "count is at " << count << endl;
++count;
}
int count;
};
However, when I try to access count
after passing it to another function, count
is still at 0.
void callNTimes( int n, boost::function<void()> func )
{
for ( int i = 0; i < n; ++i )
func();
}
int main()
{
CallCounter counter;
callNTimes( 20, counter );
cout << counter.count << endl; // prints 0
return 0;
}
Even though while counter
is being called, it's printing out the correct count
. I understand that boost::function
is making a copy of my struct counter
. Is there a way to pass it by reference so that afterwards, count
is the right number?