0

For a 'tuple-style' C++ struct, such as

struct state {
  int a, b, c;
};

how can we most quickly operator< and constructors with natural semantics (e.g. similar to those of std::pair)?

Specifically, is there a way to obtain the following methods without explicitly writing the implementation?

struct state {
    int a, b, c;
    state() { }  // a = b = c = 0
    state(int _a, int _b, int _c) {  } // a = _a, b = _b, c = _c

    bool operator<(const state& other) const {
        // first compare by a, then by b, then by c
        return (a == other.a ? (b == other.b ? (c < other.c) : b < other.b) : a < other.a)
    }
};

More generally, does any approach for when the fields are not all of the same type? For example,

struct state {
    int a, b;
    string c;
};
AustinBest
  • 23
  • 5
  • 1
    What version of C++ are you using? Also, is it really "tuple-style" if you can't get the elements with `std::get`? – Nicol Bolas Jan 02 '23 at 03:13
  • 1
    The dupe is for `operator ==` but the code is the same for `operator <`, you just have to replace the `==`'s with `<`'s – NathanOliver Jan 02 '23 at 03:14
  • Extra to the dupe, there is the [example](https://en.cppreference.com/w/cpp/utility/tuple/tie). – 273K Jan 02 '23 at 03:15
  • @NathanOliver what about constructors? – AustinBest Jan 02 '23 at 03:16
  • Also see [this](https://stackoverflow.com/a/27837789/4342498) for C++20 default comparison options. – NathanOliver Jan 02 '23 at 03:17
  • 1
    @AustinBest For the default, you can use in class initializers: `int a = 0, b = 0, c = 0;`. For the parameterized constructor no. That said, if you get rid of all the constructors your class becomes an aggregate and can be initialized like `state foo{1, 2, 3}` – NathanOliver Jan 02 '23 at 03:20

0 Answers0