Tag Archives: Anthony Williams

Using std::tie to implement operator< (by Anthony Williams at ACCU 2013)

I’ve used std::tie to unbind the underlying data from a std::tuple in the past:

auto t = std::make_tuple( 1, 42, 100 );
int a, b, c;
std::tie( a, b, c ) = t;

But I hadn’t seen this handy trick for using std::tie to implement operator<

#include <tuple>

struct S
{
  S(int a_, int b_, int c_) : a(a_), b(b_), c(c_)
  {}

  int a;
  int b;
  int c;
};

bool operator<( const S& lhs, const S& rhs )
{
  return std::tie( lhs.a, lhs.b, lhs.c )
       < std::tie( rhs.a, rhs.b, rhs.c );
}

int main()
{
  S s1( 1, 2, 3), s2 ( 1, 2, 4 ), s3 ( 0, 2, 3);

  std::cout << "s1 should be less than s2: " << (s1 < s2) << "\n"
            << "s3 should be less than s1: " << (s3 < s1) << "\n";

  return 0;
}

Notice that std::tie does not copy the variables (as per the earlier example, it takes them by reference). You can also mimic the use of use of underscore in F#

let f i = (i, i*2, i*4)
let a, _, c = f 5

using std::ignore

auto f = []( int i){ return std::tuple(i, i*2, i*4); }
int a, b;
std::tie( a, std::ignore, b ) = f( 5 );

5 Comments

Filed under C++ Code