CreFroD
CreFroD

Reputation: 97

How to apply a comparison operator to each variable in two anonymous structs?

I have a class with an anonymous struct:

class foo {
    struct {
        float x;
        float y;
        float z;
    };
};

I create two objects of this class:

obj1 = {1, 2, 3};
obj2 = {2, 3, 4};

Then I want to know if all the variables of obj2's anonymous struct are greater than the corresponding variables of the anonymous struct of obj1. Is there an easy way to do this apart from directly comparing each pair of variables and some macro stuff?

Upvotes: 1

Views: 184

Answers (3)

Slava
Slava

Reputation: 44238

You can use std::tie:

bool foo::allGreater( const &foo f ) const
{
    return not ( std::tie( x, y, z ) <= std::tie( f.x, f.y, f.z ) );
}

Upvotes: 0

Gaurav Sehgal
Gaurav Sehgal

Reputation: 7542

You could overload operators > and < for your class.This way you don't have to explicitly compare the members every time you need to compare foo objects.

class foo 
{
  //other members
  public:
  bool operator>(const foo &o)
  {
    return x>o.x && y>o.y && z>o.z;
  }
  bool operator<(const foo &o)
  {
    return x<o.x && y<o.y && z<o.z;
  }
};

and then use it as

cout<<(obj2>obj1);

Upvotes: 1

Deduplicator
Deduplicator

Reputation: 45654

As an aside, anonymous structs without name aren't a C++ feature.

And then to answer your question, no, there is no shortcut to testing whether all members of one struct are bigger than the corresponding members of a second struct.
There is only shortcut to testing whether the first non-equal corresponding member in sequence is bigger using std::tie.

Upvotes: 3

Related Questions