kreuzerkrieg
kreuzerkrieg

Reputation: 3239

How to compare tuples of different length?

I would like to write a comparator which compares tuples of different length but have the same "prefix". Consider following case, I have two tuples.

auto t1 = std::make_tuple(10, "Test1");
auto t2 = std::make_tuple(10, "Test", 3.14);


I would like to apply "less" for t1 < t2, where only two first members of tuple are compared (same type?) and the third one is just omited. Is it possible?

Upvotes: 3

Views: 682

Answers (2)

SergeyA
SergeyA

Reputation: 62613

Well, since no one has chimed in, here is the solution. It uses C++14 std::index_sequence, so the recursion is hidden in it.

#include <tuple>
#include <utility>

template<class... ARGS1, class... ARGS2, std::size_t... Is>
bool tuple_compare_helper(const std::tuple<ARGS1...>& lhs, const std::tuple<ARGS2...>& rhs, std::index_sequence<Is...> ) {
  return std::tie(std::get<Is>(lhs)...) < std::tie(std::get<Is>(rhs)...);

}

template<class... ARGS1, class... ARGS2> 
bool tuple_compare(const std::tuple<ARGS1...>& lhs, const std::tuple<ARGS2...>& rhs) {
  const auto min_size = std::min(sizeof...(ARGS1), sizeof...(ARGS2));

  return tuple_compare_helper(lhs, rhs, std::make_index_sequence<min_size>());
}

// test driver
#include <iostream>
int main() {
  auto t1 = std::make_tuple(1, std::string("One"), 2.0);
  auto t2 = std::make_tuple(3, std::string("Two"));


  std::cout << tuple_compare(t2, t1) << "\n";
}

Upvotes: 7

bisthebis
bisthebis

Reputation: 523

t1 and t2 are of purely different types,so you can't compare them. (tuples are template type; they aren't polymorphic at runtime) I think the only t-way to do this is a temporary tuple which takes t2 first and seconds elements to do the comparison

Upvotes: -6

Related Questions