Home > Software design >  Correct variadic pack expansion
Correct variadic pack expansion

Time:12-03

I am working on C 20 implementation of tuple:

template<size_t INDEX, typename T>
struct wrap { [[no_unique_address]] T data {}; };

template<typename...>
class base {};

template<size_t... INDEX, typename... Ts>
class base<index_sequence<INDEX...>, Ts...> : public wrap<INDEX, Ts>... {
public:
    constexpr base( const Ts &... args ) : /* !! HERE SHALL THE MAGIC COME */ {}
};

template<typename... Ts>
class tuple : public base<index_sequence_for<Ts...>, Ts...> {
public:
    /* Inherit base constructors */
    using base<index_sequence_for<Ts...>, Ts...>::base;
};

My question is: How to correctly implement the code in place of /* !! HERE SHALL THE MAGIC COME */ to call base, means wrap<> constructor - the wrap copy constructor taking the corresponding instance of T (expanded from base's template variadic pack Ts) hold in args?

Thanks in advance to anyone willing to help.

CodePudding user response:

Parameter pack expansion also applies to member initializer lists, so you can simply do this:

template<size_t INDEX, typename T>
struct wrap { [[no_unique_address]] T data {}; };

template<typename...>
class base {};

template<size_t... INDEX, typename... Ts>
class base<std::index_sequence<INDEX...>, Ts...> : public wrap<INDEX, Ts>... {
 public:
  constexpr base(const Ts&... args) : wrap<INDEX, Ts>{args}... {}
};

Demo.

  • Related