通过 'tuple' 和 'tie' 实现比较运算符,好主意吗?

(注意:tupletie 可以取自 Boost 或 C++11.)
在编写只有两个元素的小型结构时,我有时倾向于选择 std::pair,因为所有重要的东西都已经针对该数据类型完成了,例如 operator< 用于严格-弱排序.
缺点是几乎没有用的变量名.即使我自己创建了那个 typedef,我也不会记得 2 天后 firstsecond 到底是什么,尤其是如果它们都是同类型.这对于两个以上的成员来说会变得更糟,因为嵌套 pair 非常糟糕.
另一个选项是 tuple,来自 Boost 或 C++11,但这看起来并没有更好更清晰.所以我回去自己编写结构,包括任何需要的比较运算符.
因为尤其是 operator< 可能非常麻烦,所以我想通过仅依靠为 tuple 定义的操作来规避这整个混乱:

(Note: tuple and tie can be taken from Boost or C++11.)
When writing small structs with only two elements, I sometimes tend to choose a std::pair, as all important stuff is already done for that datatype, like operator< for strict-weak-ordering.
The downsides though are the pretty much useless variable names. Even if I myself created that typedef, I won't remember 2 days later what first and what second exactly was, especially if they are both of the same type. This gets even worse for more than two members, as nesting pairs pretty much sucks.
The other option for that is a tuple, either from Boost or C++11, but that doesn't really look any nicer and clearer. So I go back to writing the structs myself, including any needed comparision operators.
Since especially the operator< can be quite cumbersome, I thought of circumventing this whole mess by just relying on the operations defined for tuple:

operator< 示例,例如对于严格-弱排序:

Example of operator<, e.g. for strict-weak-ordering:

bool operator<(MyStruct const& lhs, MyStruct const& rhs){
  return std::tie(lhs.one_member, lhs.another, lhs.yet_more) <
         std::tie(rhs.one_member, rhs.another, rhs.yet_more);
}

(tie 从传递的参数中创建一个 T& 引用的 tuple.)

(tie makes a tuple of T& references from the passed arguments.)

编辑:@DeadMG 提出的从 tuple 私有继承的建议不错,但也有不少缺点:

Edit: The suggestion from @DeadMG to privately inherit from tuple isn't a bad one, but it got quite some drawbacks:

  • 如果运营商是独立的(可能是朋友),我需要公开继承
  • 通过强制转换,可以轻松绕过我的函数/运算符(特别是 operator=)
  • 使用 tie 解决方案,如果某些成员对排序无关紧要,我可以忽略它们
  • If the operators are free-standing (possibly friends), I need to inherit publicly
  • With casting, my functions / operators (operator= specifically) can be easily bypassed
  • With the tie solution, I can leave out certain members if they don't matter for the ordering

我需要考虑此实现中的任何缺点吗?

Are there any drawbacks in this implementation that I need to consider?

推荐答案

这肯定会让编写一个正确的运算符比自己滚动它更容易.如果分析显示比较操作是您的应用程序的一个耗时部分,我会说只考虑一种不同的方法.否则,维护它的便利性应该超过任何可能的性能问题.

This is certainly going to make it easier to write a correct operator than rolling it yourself. I'd say only consider a different approach if profiling shows the comparison operation to be a time-consuming part of your application. Otherwise the ease of maintaining this should outweigh any possible performance concerns.

相关文章