How to compare tuples of different length?

对着背影说爱祢 提交于 2019-12-12 16:11:01

问题


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?


回答1:


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";
}



回答2:


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



来源:https://stackoverflow.com/questions/35563209/how-to-compare-tuples-of-different-length

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!