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?

5
  • 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. Commented Jan 25, 2018 at 18:12
  • As I know, std::tie requires an comparison operator implemented in the struct. My struct does not have one. Commented Jan 25, 2018 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 Commented Jan 25, 2018 at 18:19
  • Why do you need this anonymous struct anyway? It does not make any sense Commented Jan 25, 2018 at 18:20
  • C++ Disallows anonymous structs. It is an extension. Please check the documentation. Similar question : stackoverflow.com/q/2253878/2504757. Commented Jan 25, 2018 at 18:25

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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 ) );
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.