Martin Kopecký
Martin Kopecký

Reputation: 1010

Correct variadic pack expansion

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.

Upvotes: 0

Views: 102

Answers (1)

康桓瑋
康桓瑋

Reputation: 43016

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.

Upvotes: 2

Related Questions