通过'tuple'和'tie'实现比较运算符,一个好主意? [英] Implementing comparison operators via 'tuple' and 'tie', a good idea?

查看:175
本文介绍了通过'tuple'和'tie'实现比较运算符,一个好主意?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

(注意: tuple tie 可以取自Boost或C ++ 11。

当编写只有两个元素的小结构时,我有时会选择一个 std :: pair ,因为所有重要的东西已经为该数据类型完成,如运算符< 用于严格弱排序。

这些缺点是几乎没有用的变量名。即使我自己创造了 typedef ,我不会记得2天后第一和什么 second 确切地是,特别是如果他们都是相同的类型。对于两个以上的成员来说,这种情况变得更糟,因为嵌套很糟糕。

其他选项是 tuple ,无论是从Boost还是C ++ 11,但这不是真的看起来更好更清晰。所以我回到自己写结构体,包括任何需要的比较运算符。

由于特别是运算符< 可能相当麻烦,只需依靠为 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:

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

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 a tuple of T& 引用来自传递的参数。)

(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:


  • 如果操作符是独立的(可能是朋友),我需要继承public

  • 通过转换,可以轻松绕过我的函数/运算符( 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.

这篇关于通过'tuple'和'tie'实现比较运算符,一个好主意?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆