1

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?

CreFroD
  • 97
  • 1
  • 11
  • 3
    `std::tie` would not be used to check whether **all** of the variables are bigger. Only whether the first non-equal one is bigger. – Deduplicator Jan 25 '18 at 18:12
  • As I know, std::tie requires an comparison operator implemented in the struct. My struct does not have one. – CreFroD Jan 25 '18 at 18:16
  • @CreFroD `std::tie` is an easy way to create a comparison operator for set of fields. But it would not work in your case as comparison on `std::tuple` works different – Slava Jan 25 '18 at 18:19
  • Why do you need this anonymous `struct` anyway? It does not make any sense – Slava Jan 25 '18 at 18:20
  • C++ Disallows anonymous structs. It is an extension. Please check the documentation. Similar question : https://stackoverflow.com/q/2253878/2504757. – Robert Andrzejuk Jan 25 '18 at 18:25

3 Answers3

3

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.

Deduplicator
  • 44,692
  • 7
  • 66
  • 118
1

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);
Gaurav Sehgal
  • 7,422
  • 2
  • 18
  • 34
0

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 ) );
}
Slava
  • 43,454
  • 1
  • 47
  • 90