Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ - Checking all member variables for condition

Tags:

c++

class

member

Simplified example of my situation:

I have a class with 3 member variables, all integers, e.g.

class Foo
{
   public:
      int A;
      int B;
      int C;
};

I want to have a function that returns a Boolean true if all of the member variables are 0 and false otherwise.

Easy enough, could be accomplished with this member function:

bool all_zero()
{
   return (A == 0 && B == 0 && C == 0);
}

I can do this if necessary.

However, this is not ideal in my situation because:

  1. I am not the only person who manages this software.

  2. Occasionally, new member variables are added to this class (e.g. int D).

  3. This is a very large C++ project, and we often don't add new member variables to the class directly by manually modifying the code - instead, we have custom tools that automatically modify the code for us. Therefore, it is pretty rare that we make manual modification to this class.

  4. Additionally, since this project is so large, the all_zero function above could easily be overlooked (i.e. someone could forget, or be completely unaware to add && D == 0 to the function if a new member variable is added).

All that said... here is my question:

Is there any way to modify this all_zero function such that it always checks all member variables (of int type), without needing to tell the function to explicitly check each one? By the way, I am also OK if this functionality is accomplished outside of the class (rather than inside the class with a member function).

I am hoping that I don't have to resort to this, but worst case scenario for me here is that I can stick with this original all_zero idea above and just proceduralize the adding of a new member variable to this class, basically telling anyone who adds a member variable to the class must also manually modify this all_zero function.

like image 300
ImaginaryHuman072889 Avatar asked Jan 25 '18 12:01

ImaginaryHuman072889


1 Answers

bool all_zero() const
{
   Foo f{}, g{};
   g = *this;  
   return ::memcmp(&f, &g, sizeof(f));
}

is one way, assuming your class is trivially copyable. The {} will zero-initialise the members including any padding bits, and the compiler generated assignment operator will copy the members for comparison.

Quite possibly we will soon get a compiler-generated == which would probably be better. See https://isocpp.org/blog/2016/02/a-bit-of-background-for-the-default-comparison-proposal-bjarne-stroustrup.

Finally, if the comparison method needs to be outside the class, then consider

bool all_zero(const Foo& f)
{
    Foo g{}, h{};
    h = f;
    return ::memcmp(&g, &h, sizeof(f));
}
like image 92
Bathsheba Avatar answered Oct 22 '22 21:10

Bathsheba