I have a class with a method that performs some checks on some variables and returns a value and, eventually, prints a warning message. As the method doesn't change any class variable, I've defined it as const. However to avoid to flood the output I would like to suppress the warning printing after few (or just one) prints. I've not been able to find a solution keeping the method const, is that possible (easy)?
How about use mutable
counter? I think, it should be acceptable, since it's not state of object, it's internal logic state.
Something like this
class Printer
{
public:
Printer() : counter(0) {}
void output() const
{
if (counter++ < max_warnings)
{
std::cout << "Something special" << std::endl;
}
}
private:
static const size_t max_warnings = 5;
mutable size_t counter;
};
Live example
Since there are many comments about multithreading, example with atomic counter
class Printer
{
public:
Printer() : counter(0) {}
void output() const
{
if (counter++ < max_warnings)
{
std::cout << "Something special" << std::endl;
}
}
private:
static const size_t max_warnings = 5;
mutable std::atomic<size_t> counter;
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With