4

Why isn't it possible to compare two tuples of different size like this:

#include <tuple>
int main() {
  std::tuple<int, int> t1(1, 2);
  std::tuple<int> t2(1);
  if(std::tuple_size<decltype(t1)>::value == std::tuple_size<decltype(t2)>::value)
    return (t1 == t2);
  else
    return 0;
}

I know that t1==t2 is not possible. But in this example it wouldn't be executed. Is there a possibility to compare tuples of different sizes?

Piotr Skotnicki
  • 46,953
  • 7
  • 118
  • 160
wapitifass
  • 39
  • 3

3 Answers3

4

operator== requires the tuples to be of equal lengths.

§ 20.4.2.7 [tuple.rel]:

template<class... TTypes, class... UTypes>
constexpr bool operator==(const tuple<TTypes...>& t, const tuple<UTypes...>& u);

1 Requires: For all i, where 0 <= i and i < sizeof...(TTypes), get<i>(t) == get<i>(u) is a valid expression returning a type that is convertible to bool. sizeof...(TTypes) == sizeof...(UTypes).

If you want two tuples of different lengths to be considered unequal, you'd need to implement this logic yourself:

template <typename... Ts, typename... Us>
auto compare(const std::tuple<Ts...>& t1, const std::tuple<Us...>& t2)
    -> typename std::enable_if<sizeof...(Ts) == sizeof...(Us), bool>::type
{
    return t1 == t2;
}

template <typename... Ts, typename... Us>
auto compare(const std::tuple<Ts...>& t1, const std::tuple<Us...>& t2)
    -> typename std::enable_if<sizeof...(Ts) != sizeof...(Us), bool>::type
{
    return false;
}

DEMO

This way, the code comparing two tuples, t1 == t2, is instantiated only when the lengths of tuples match each other. In your scenario, a compiler is unable to compile your code, since there is no predefined operator== for such a case.

Community
  • 1
  • 1
Piotr Skotnicki
  • 46,953
  • 7
  • 118
  • 160
1

You may write several overloads:

template<typename ...Ts>
bool is_equal(const std::tuple<Ts...>& lhs, const std::tuple<Ts...>& rhs)
{
    return lhs == rhs;
}

template<typename ...Ts, typename... Us>
bool is_equal(const std::tuple<Ts...>&, const std::tuple<Us...>&)
{
    return false;
}

Live example

Jarod42
  • 203,559
  • 14
  • 181
  • 302
-1

You have problem with size mismatch. Read this, maybe it can help you. Implementing comparison operators via 'tuple' and 'tie', a good idea?

Community
  • 1
  • 1
Richard Rublev
  • 7,718
  • 16
  • 77
  • 121
  • I've edited your answer to make the link functional, though this would IMHO be better posted as a comment rather than an answer, since it's essentially a link-only response. – enhzflep Aug 14 '15 at 11:55