I have a time domain simulation running timesteps are adaptive and may grow or shrink, so there aren't a fixed number of steps to a constant time.
I want to produce an output every (simulation) time interval (eg 1 second), but this does not correlate with a fixed number of steps.
There is a method which gets called every step (both the time and step count are arguments), but I only want it to return true once a second.
This method is currently declared const.
(Timesteps will typically be 1000-per-second so I don't need to make provision for the case where one step completely oversteps a time interval).
I don't know how I make this perform actions once per second, without refactoring to remove the const flag.
I can achieve the once per second output if I make the functor stateful and record the previous time which was reported. However I would prefer not to make the method non-const as this will:
- need to propagate non-const to all invoking methods (a step backwards)
- require refactoring of the invoking code (not a big problem)
- risk race conditions when we try to use it in multithreaded settings
Note: I know I could use const_cast or raw pointers to achieve the mutability despite const, but this is not a good solution and won't help the race conditions/multithreading risks.
My functor class (which currently won't compile due to the cost)
class FixedTimeOutputDecider {
/// <summary>
/// This should return true once per "regularity" which defaults to once per second
/// </summary>
public:
FixedTimeOutputDecider(double regularity = 1.0) : _regularity(regularity), _next_output_time(0) {}
bool should_output(int step, double time) const {
if (time > _next_output_time) {
// the next time to output should be the next integer*regularity
_next_output_time = (int(floor(time / _regularity)) + 1) * _regularity;
return true;
} else {
return false;
}
}
bool operator()(int step, double time /*extra data here*/) const {
if(should_output(step, time)){
//Outputing code here
}
}
private:
const double _regularity;
double _next_output_time;
};
Is it possible to output once per second in a stateless functor given the irregular step size?
Edit: Following comments/questions about the context and surrounding code, here is a bigger (not minimal) example of the use of the class https://godbolt.org/z/jecaMnx7o .
constmember function, then sometimes amutablemember variable is the answer..constismutable. It is something that's usually better to avoid, but so are the alternatives you listed. Wasmutableoverlooked?