Abyx
Abyx

Reputation: 12928

Why make_tie is not a thing?

There is a popular idiom using std::tie to implement comparison operators:

// foo.h
struct Foo {
  int a, b;
  string c;

  bool operator<(const Foo& rhs) const;
};

// foo.cc
bool Foo::operator<(const Foo& rhs) const {
  return tie(a, b, c) < tie(rhs.a, rhs.b, rhs.c);
}

E.g. it's widely used in Chromium

However it requires copying the list of members, so why not write a helper function:

static auto MakeTie(const Foo& x) {
  return tie(x.a, x.b, x.c);
}
bool Foo::operator<(const Foo& rhs) const {
  return MakeTie(*this) < MakeTie(rhs);
}

// or, in foo.h
auto MakeTie() const;
// and in foo.cc
auto Foo::MakeTie() const { ... }

(btw such member function cannot be called from any other translation unit)

So, why do I see hundreds of such tie(a, b, c) < tie(copy-pasta) pairs, is there a reason behind this?

Upvotes: 0

Views: 166

Answers (1)

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385405

Firstly, if your class has so many members that doubling up tie is problematic, then you may have a design smell anyway.

I would tend to agree that this is a bit of an annoyance, but remember that it's not the reason for tie's being. There is no such thing as "a tie"; "tie" here is a verb, a way to describe how expressions are being "tied together" into what is actually a tuple of references.

You can of course write your own replacement for tie that knows how all the relevant members of your class, so that this does not need writing out twice. You could call it members_as_tuple. It's up to you as to whether you want to do that, just as it is up to you whether to make any function to avoid some particular duplicated code.

Certainly, though, without reflection, C++ cannot do this for you in the general case, so that's why such a facility isn't provided out of the box.

tl;dr: You've already shown the best (only?) way to do it, but I wouldn't call it make_tie.


As for why people aren't doing this more, well, that's unanswerable. They probably just didn't think of it, or didn't think they needed it, and were probably right.

Upvotes: 6

Related Questions