vendredi 26 août 2022

Why this two different implementations of Tuple have a different size?

I have two different implementations of a Tuple class template. One with specialization for any number of arguments and one using variadic templates. When using an empty class for some of the tuple elements the two implementations have different sizes. Why does the second one using a variadic template have a bigger size and is it possible to be fixed to have the same size as the first one?

#include <iostream>

using namespace std;

struct Nil {};

template <typename T1 = Nil, typename T2 = Nil>
struct Tuple1 : Tuple1<T2>
{
  T1 x;

  using Base = Tuple1<T2>;

  Base* base() { return static_cast<Base*>(this); }
  const Base* base() const { return static_cast<const Base*>(this); }

  Tuple1(const T1& t1, const T2& t2)
    : Base{ t2 }, x{ t1 } {}
};

template <> struct Tuple1<> {};

template <typename T1>
struct Tuple1<T1> : Tuple1<>
{
  T1 x;

  using Base = Tuple1<>;

  Base* base() { return static_cast<Base*>(this); }
  const Base* base() const { return static_cast<const Base*>(this); }

  Tuple1(const T1& t1)
    : Base{}, x{ t1 } {}
};

// ---------------------------------------------------------------------------

template <typename...> struct Tuple2;

template <> struct Tuple2<> {};

template <typename Head, typename... Tail>
struct Tuple2<Head, Tail...> : Tuple2<Tail...>
{
  Tuple2(const Head& head, const Tail&... tail)
    : Base{ tail... }, m_head{ head } {}

private:
  using Base = Tuple2<Tail...>;
  Head m_head;
};

int main()
{
  cout << "Tuple1 sizes:\n";
  cout << sizeof(Tuple1<>) << '\n';
  cout << sizeof(Tuple1<int*>) << '\n';
  cout << sizeof(Tuple1<int*, Nil>) << '\n';

  cout << '\n';

  cout << "Tuple2 sizes:\n";
  cout << sizeof(Tuple2<>) << '\n';
  cout << sizeof(Tuple2<int*>) << '\n';
  cout << sizeof(Tuple2<int*, Nil>) << '\n';

  return 0;
}

The result of the execution of the program with MSVC 2022 is the following:

Tuple1 sizes:
1
8
8

Tuple2 sizes:
1
8
16

Aucun commentaire:

Enregistrer un commentaire