有一个流行的习惯用法std::tie用来实现比较运算符:
// 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);
}
但是它需要复制成员列表,所以为什么不编写一个辅助函数:
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 { ... }
(顺便说一句,不能从任何其他翻译单元调用此类成员函数)
那么,为什么我会看到数百对这样的tie(a, b, c) < tie(copy-pasta)对,这背后有什么原因吗?