Changing the value of a tracking item variable

I want to track when a member variable changes value, so I can print it. Now the obvious solution for this is to add a tracking function to the member method Set, for example:

class Foo
{
public:
    Foo() {}

    void SetBar(int value)
    {
        //Log that m_bar is going to be changed
        m_bar = value;
    }
private:
    int m_bar; // the variable we want to track
};

The problem I am facing is that I am working on a huge project, and some classes have many methods that internally change member variables instead of calling their Setters.

m_bar = somevalue;

Instead:

SetBar(somevalue);

So, I am wondering if there is a faster / cleaner method for achieving what I want, than just changing each m_bar =to SetBar(. An assignment operator can only overload this member variable, perhaps?

+4
1

, .

:

#include <iostream>

template <class T>
class Logger
{
  T value;

public:

  T& operator=(const T& other)
  {
    std::cout << "Setting new value\n";
    value = other;
    return value;
  }

  operator T() const
  {
    return value;
  }

};

class Foo
{
public:
    Foo() {}

    void SetBar(int value)
    {
        //Log that m_bar is going to be changed
        m_bar = value;
    }

private:

#if 1
    Logger<int> m_bar; // the variable we want to track
#else
    int m_bar; // the variable we want to track
#endif

};

int main()
{
  auto f = Foo();
  f.SetBar(12);
}

ideone.

+3

Source: https://habr.com/ru/post/1616938/


All Articles