Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
242 views
in Technique[技术] by (71.8m points)

c++ - Implementing comparison operators via 'tuple' and 'tie', a good idea?

(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 makes a tuple of T& references from the passed arguments.)


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

  • 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?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...