operator< comparing multiple fields

前端 未结 6 826
北海茫月
北海茫月 2020-11-28 13:03

I have the following operator< that is supposed to sort first by a value, then by another value:

    inline bool operator < (const obj& a, const ob         


        
6条回答
  •  执念已碎
    2020-11-28 13:15

    You can use variadic templates in c++11 or later

    template
    bool less_than( const T& a, const T& b )
    {
        return a < b;
    }
    
    template
    bool less_than( const T& a, const T& b, Args... args )
    (
        if ( a < b )
              return true;
        else if ( b < a )
              return false;
        else
              return less_than(  args...  );
    )
    

    Then you would call as

    return less_than(a.x,b.x,
                     a.y,b.y,
                     a.z,b.z);
    

    It supports any number of fields or types as long as type has < operator. You can mix types.

提交回复
热议问题