Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Suppress messages printing from a const method

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)?

like image 584
DarioP Avatar asked Nov 01 '13 09:11

DarioP


1 Answers

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;
};
like image 94
ForEveR Avatar answered Oct 24 '22 21:10

ForEveR