Is there a convenient way to wrap std::pair as a new type?

后端 未结 8 1087
梦谈多话
梦谈多话 2021-02-02 17:02

Often times I find myself using std::pair to define logical groupings of two related quantities as function arguments/return values. Some examples: row/col, tag/value, etc.

相关标签:
8条回答
  • 2021-02-02 17:31

    You can use some standard utility templates that help define the relation operators.

    #include <utility>

    http://www.sgi.com/tech/stl/operators.html

    Requirements on types

    The requirement for operator!= is that x == y is a valid expression
    The requirement for operator> is that y < x is a valid expression
    The requirement for operator<= is that y < x is a valid expression
    The requirement for operator>= is that x < y is a valid expression

    So basically it will automatically generate the other operators give < and == all you have to do is include <utility>

    0 讨论(0)
  • 2021-02-02 17:32

    Unfortunately strong typedefs will not make it into C++0x, it has been given the classification of Not ready for C++0x, but open to resubmit in future.

    0 讨论(0)
  • 2021-02-02 17:38

    A coworker pointed me to two possible solutions:

    Using boost strong typedef as an improved version of the typedef. I'd never heard of this before, and it doesn't seem to really be part of any sub-library, just kind of floating.

    Using a macro to generate the code needed for the different operators. This way I wouldn't have to explicitly write anything on a per definition level, just do something like DEFINE_PAIR_TYPE(Position, int, int, row, col);. This is probably closest to what I'm looking for, but it still feels kind of evil compared to some of the solutions presented by others.

    0 讨论(0)
  • 2021-02-02 17:42

    This is what Boost.Tuple was made for.

    But you should probably be using std::tuple now...

    0 讨论(0)
  • 2021-02-02 17:44

    There's also the Boost::Operators library to automatically generate operator code. It's similar to the SGI library that Martin York suggested, but might be more portable.

    0 讨论(0)
  • 2021-02-02 17:47

    You can still reuse the pair functionality by forwarding to it:

    bool operator< ( const Position &a, const Position &b ) 
    {
        return
            std::make_pair( a.row, a.col ) < std::make_pair( b.row, b.col );
    }
    

    Although you still end up with doing this for every operatory you need...

    0 讨论(0)
提交回复
热议问题